"use client"

import type React from "react"
import { useState } from "react"
import {
  Box,
  Stack,
  Paper,
  Typography,
  IconButton,
  Checkbox,
  ListItemText,
  CircularProgress,
  Menu,
  MenuItem,
  Divider,
} from "@mui/material"
import {
  MoreVert as MoreVertIcon,
  Star as StarIcon,
  StarBorder as StarBorderIcon,
  Download as DownloadIcon,
  Share as ShareIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
} from "@mui/icons-material"
import type { DocumentDTO } from "@/shared/types/document"
import FileThumbnail from "@/shared/components/file-thumbnail"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

interface DocumentCardProps {
  document: DocumentDTO
  selected?: boolean
  onSelect?: (id: number) => void
  onClick?: () => void
  onMarkAsFavorite?: (id: number) => void
  onUnmarkAsFavorite?: (id: number) => void
  loadingDocuments?: Record<number, boolean>
}

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return "0 Bytes"
  const k = 1024
  const sizes = ["Bytes", "KB", "MB", "GB"]
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Number.parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]
}

const formatDocumentType = (type: string): string => {
  const typeMap: Record<string, string> = {
    WORK_CERTIFICATE: "Certificat de travail",
    PRESENCE_CERTIFICATE: "Certificat de présence",
    ID_CARD: "Carte d'identité",
    DRIVER_LICENCE: "Permis de conduire",
  }
  return typeMap[type] || type
}

export default function DocumentCard({
  document,
  selected = false,
  onSelect,
  onClick,
  onMarkAsFavorite,
  onUnmarkAsFavorite,
  loadingDocuments = {},
  ...other
}: DocumentCardProps) {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
  const [showCheckbox, setShowCheckbox] = useState(false)
  const [isFavorite, setIsFavorite] = useState(document.favorite || false)
  const open = Boolean(anchorEl)

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    event.stopPropagation()
    setAnchorEl(event.currentTarget)
  }

  const handleClose = () => {
    setAnchorEl(null)
  }

  const handleMenuItemClick = (e: React.MouseEvent) => {
    e.stopPropagation()
    handleClose()
  }

  const handleFavoriteClick = (event: React.ChangeEvent<HTMLInputElement>) => {
    event.stopPropagation()
    if (isFavorite && onUnmarkAsFavorite) {
      onUnmarkAsFavorite(document.id)
    } else if (!isFavorite && onMarkAsFavorite) {
      onMarkAsFavorite(document.id)
    }
    setIsFavorite(!isFavorite)
  }

  return (
    <Stack
      component={Paper}
      variant="outlined"
      spacing={1}
      alignItems="flex-start"
      sx={{
        p: 2.5,
        maxWidth: 300,
        borderRadius: 2,
        cursor: "pointer",
        position: "relative",
        transition: "transform 0.2s, box-shadow 0.2s",
        "&:hover": {
          transform: "translateY(-4px)",
          boxShadow: 4,
        },
      }}
      onClick={onClick}
      onMouseEnter={() => setShowCheckbox(true)}
      onMouseLeave={() => setShowCheckbox(false)}
    >
      <Box sx={{ position: "relative", display: "inline-block" }}>
        <FileThumbnail file={document.contentType || "PDF"} sx={{ width: 36, height: 36 }} />
      </Box>

      <Stack
        direction="row"
        alignItems="center"
        sx={{
          top: 8,
          right: 8,
          position: "absolute",
        }}
      >
        <Checkbox
          color="warning"
          icon={<StarBorderIcon />}
          checkedIcon={<StarIcon />}
          checked={isFavorite}
          onChange={handleFavoriteClick}
          onClick={(e) => e.stopPropagation()}
          size="small"
          sx={{
            p: 0.3,
          }}
        />
        <IconButton onClick={handleClick} disabled={loadingDocuments[document.id]} size="small">
          <ConditionalComponent
            isValid={loadingDocuments[document.id]}
            defaultComponent={<MoreVertIcon fontSize="small" />}
          >
            <CircularProgress size={20} />
          </ConditionalComponent>
        </IconButton>
      </Stack>

      <ListItemText
        primary={document.name}
        secondary={
          <Stack
            sx={{
              width: "100%",
              color: "text.disabled",
            }}
          >
            <Typography
              variant="caption"
              noWrap
              sx={{
                display: "flex",
                alignItems: "center",
              }}
            >
              {formatFileSize(document.size)} • {document.contentType}
            </Typography>

            <Typography
              variant="caption"
              noWrap
              sx={{
                display: "flex",
                alignItems: "center",
              }}
            >
              {formatDocumentType(document.documentType)}
            </Typography>
          </Stack>
        }
        primaryTypographyProps={{
          noWrap: true,
          typography: "body2",
          mb: 2,
        }}
        sx={{
          minWidth: 0,
          width: "100%",
        }}
      />

      <Menu anchorEl={anchorEl} open={open} onClose={handleClose} onClick={(e) => e.stopPropagation()}>
        <MenuItem onClick={handleMenuItemClick}>
          <DownloadIcon fontSize="small" sx={{ mr: 1 }} />
          Télécharger
        </MenuItem>
        <MenuItem onClick={handleMenuItemClick}>
          <ShareIcon fontSize="small" sx={{ mr: 1 }} />
          Partager
        </MenuItem>
        <MenuItem onClick={handleMenuItemClick}>
          <EditIcon fontSize="small" sx={{ mr: 1 }} />
          Renommer
        </MenuItem>
        <Divider />
        <MenuItem onClick={handleMenuItemClick} sx={{ color: "error.main" }}>
          <DeleteIcon fontSize="small" sx={{ mr: 1 }} />
          Supprimer
        </MenuItem>
      </Menu>
    </Stack>
  )
}
