"use client"

import type React from "react"
import { useEffect, 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,
  Info as InfoIcon,
  DriveFileMove as DriveFileMoveIcon,
} 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"
import RenameDocumentDialog from "./RenameDocDialog"
import ConfirmDocumentDeleteDialog from "./ConfirmDocumentDeleteDialog"

interface DocumentCardProps {
  document: DocumentDTO
  selected?: boolean
  onSelect?: (id: number) => void
  onClick?: () => void
  onMarkAsFavorite?: () => void;
  onUnmarkAsFavorite?: () => void;
  loadingDocuments?: Record<number, boolean>
  onDownload?: (document : DocumentDTO) => void;
  onShare?: (targetUserUuid: string) => void;
  onRename?: (newName: string) => void;
  onDelete?: () => void;
  onShowDetails?: () => void;
  onMove?: () => void;
}

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 = {},
  onDownload,
  onDelete,
  onRename,
  onShare,
  onShowDetails,
  onMove,
  ...other
}: DocumentCardProps) {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
  const [showCheckbox, setShowCheckbox] = useState(false)
  const [isFavorite, setIsFavorite] = useState(document.favorite || false)
  const [renameDialogOpen, setRenameDialogOpen] = useState(false)
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const open = Boolean(anchorEl)

  useEffect(() => {
  setIsFavorite(document.favorite || false);
}, [document.favorite]);

  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.MouseEvent) => {
  event.stopPropagation();
  
  if (isFavorite && onUnmarkAsFavorite) {
    onUnmarkAsFavorite();
  } else if (!isFavorite && onMarkAsFavorite) {
    onMarkAsFavorite();
  }
  
  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}
            onClick={handleFavoriteClick}
            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={(e) => {
            e.stopPropagation();
            handleMenuItemClick(e);
            onDownload?.(document);
          }}>
          <DownloadIcon fontSize="small" sx={{ mr: 1 }} />
          Télécharger
        </MenuItem>
        <MenuItem
          onClick={(e) => {
            e.stopPropagation();
            handleMenuItemClick(e);
            const targetUserUuid = prompt("Enter user UUID to share with:");
            if (targetUserUuid) {
              onShare?.(targetUserUuid);
            }
          }}>
          <ShareIcon fontSize="small" sx={{ mr: 1 }} />
          Partager
        </MenuItem>
        <MenuItem
          onClick={(e) => {
            e.stopPropagation();
            handleMenuItemClick(e);
            setRenameDialogOpen(true);
          }}>
          <EditIcon fontSize="small" sx={{ mr: 1 }} />
          Renommer
        </MenuItem>
          <MenuItem
            onClick={(e) => {
              e.stopPropagation();
              handleMenuItemClick(e);
              onShowDetails?.();
            }}>
            <InfoIcon fontSize="small" sx={{ mr: 1 }} />
            Détails
          </MenuItem>
          <MenuItem
            onClick={(e) => {
              e.stopPropagation();
              handleMenuItemClick(e);
              onMove?.();
            }}>
            <DriveFileMoveIcon fontSize="small" sx={{ mr: 1 }} />
            Déplacer
          </MenuItem>
        <Divider />
        <MenuItem
          onClick={(e) => {
            e.stopPropagation();
            handleMenuItemClick(e);
            setDeleteDialogOpen(true);
          }}
          sx={{ color: "error.main" }}>
          <DeleteIcon fontSize="small" sx={{ mr: 1 }} />
          Supprimer
        </MenuItem>
      </Menu>
    </Stack>
    <RenameDocumentDialog
        open={renameDialogOpen}
        onClose={() => setRenameDialogOpen(false)}
        onRename={(newName) => {
          onRename?.(newName);
          setRenameDialogOpen(false);
        }}
        initialName={document.name}
      />
      <ConfirmDocumentDeleteDialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
        onConfirm={() => {
          onDelete?.();
          setDeleteDialogOpen(false);
        }}
        documentName={document.name}
      />
    </>
  )
}
