"use client"

import type React from "react"

import { useState } from "react"
import { Box, Stack, Paper, IconButton, Menu, MenuItem, Checkbox, ListItemText, CircularProgress } from "@mui/material"
import {
  MoreVert as MoreVertIcon,
  Delete as DeleteIcon,
  Share as ShareIcon,
  Edit as EditIcon,
  Star as StarIcon,
  StarBorder as StarBorderIcon,
  DriveFileMove,
  Info,
} from "@mui/icons-material"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import type { FolderDTO } from "@/shared/types/document"
import DownloadIcon from '@mui/icons-material/Download';
import { useFolderStore } from "@/shared/api/stores/document-service/folderStore"


interface FolderProps {
  folder: FolderDTO
  onClick?: () => void
  onMarkAsFavorite?: (id: number) => void
  onUnmarkAsFavorite?: (id: number) => void
  loadingFolders?: Record<number, boolean>
  onRename?: (folder: FolderDTO) => void;
  onMove?: (folder: FolderDTO) => void;
  onDelete?: (folder: FolderDTO) => void;
  onShowDetails?: (folder: FolderDTO) => void;
}

export default function FolderCard({
  folder,
  onClick,
  onMarkAsFavorite,
  onUnmarkAsFavorite,
  loadingFolders = {},
  onRename,
  onMove,
  onDelete,
  onShowDetails
}: FolderProps) {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
  const [showCheckbox, setShowCheckbox] = useState(false)
  const [isFavorite, setIsFavorite] = useState(folder.favorite || false)
  const open = Boolean(anchorEl)
  const folderStore = useFolderStore();
  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 = async (event: React.ChangeEvent<HTMLInputElement>) => {
  event.stopPropagation();
  try {
    if (isFavorite) {
      await folderStore.toggleUnfavorite(folder.id, 4);
      onUnmarkAsFavorite?.(folder.id);
    } else {
      await folderStore.toggleFavorite(folder.id, 4);
      onMarkAsFavorite?.(folder.id);
    }
    setIsFavorite(!isFavorite);
  } catch (error) {
    console.error("Erreur lors de la mise à jour des favoris :", error);
  }
};


  const fileCount = folder.documents?.length || 0

  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" }}>
        <Box component="img" src="/assets/icons/files/ic_folder.svg" 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={loadingFolders[folder.id]} size="small">
          <ConditionalComponent
            isValid={loadingFolders[folder.id]}
            defaultComponent={<MoreVertIcon fontSize="small" />}
          >
            <CircularProgress size={20} />
          </ConditionalComponent>
        </IconButton>
      </Stack>

      <ListItemText
        primary={folder.name}
        secondary={
          <Stack
            direction="row"
            alignItems="center"
            sx={{
              maxWidth: 0.99,
              whiteSpace: "nowrap",
              typography: "caption",
              color: "text.disabled",
            }}
          >
            {`${fileCount} ${fileCount === 1 ? "fichier" : "fichiers"}`}
          </Stack>
        }
        primaryTypographyProps={{
          noWrap: true,
          typography: "subtitle2",
        }}
        secondaryTypographyProps={{
          mt: 0.5,
          component: "span",
          alignItems: "center",
          typography: "caption",
          display: "inline-flex",
        }}
      />

      <Menu anchorEl={anchorEl} open={open} onClose={handleClose} onClick={(e) => e.stopPropagation()}>
        <MenuItem onClick={(e) => {
          handleMenuItemClick(e);
          onRename?.(folder);
        }}>
          <EditIcon fontSize="small" sx={{ mr: 1 }} />
          Renommer
        </MenuItem>
        <MenuItem onClick={handleMenuItemClick}>
          <ShareIcon fontSize="small" sx={{ mr: 1 }} />
          Partager
        </MenuItem>
        <MenuItem
          onClick={(e) => {
            handleMenuItemClick(e);
            onMove?.(folder);
          }}
        >
          <DriveFileMove fontSize="small" sx={{ mr: 1 }} />
          Déplacer
        </MenuItem>
        <MenuItem onClick={(e) => {
          handleMenuItemClick(e);
          onShowDetails?.(folder);
        }}>
          <Info fontSize="small" sx={{ mr: 1 }} />
          Détails
        </MenuItem>
        <MenuItem
  onClick={(e) => {
    handleMenuItemClick(e);
    folderStore.downloadZip(folder.id, folder.name);
  }}
>
  <DownloadIcon fontSize="small" sx={{ mr: 1 }} />
  Télécharger ZIP
</MenuItem>
        <MenuItem
          onClick={(e) => {
            handleMenuItemClick(e);
            onDelete?.(folder);
          }}>
          <DeleteIcon fontSize="small" sx={{ mr: 1 }} />
          Supprimer
        </MenuItem>
      </Menu>
    </Stack>
  )
}
