import { useState, useCallback } from 'react';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Avatar from '@mui/material/Avatar';
import Divider from '@mui/material/Divider';
import MenuItem from '@mui/material/MenuItem';
import Checkbox from '@mui/material/Checkbox';
import { CardProps } from '@mui/material/Card';
import IconButton from '@mui/material/IconButton';
import ListItemText from '@mui/material/ListItemText';
import { fDateTime } from '@/utils/format-time';
import { useBoolean } from '@/hooks/use-boolean';
import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard';

import { fData } from '@/utils/format-number';

import Iconify from '@/shared/components/iconify';
import { useSnackbar } from '@/shared/components/snackbar';
import { ConfirmDialog } from '@/shared/components/custom-dialog';
import CustomPopover, { usePopover } from '@/shared/components/custom-popover';
import { AccessLevel, fileManagerApi } from '@/shared/api/file-manager';

import { IFolderManager } from '@/shared/types/file';

import FileManagerShareDialog from './file-manager-share-dialog';
import FileManagerFileDetails from './file-manager-file-details';
import FileManagerNewFolderDialog from './file-manager-new-folder-dialog';
import MoveDialog from '@/shared/components/dialog/move-dialog';
import { usePermissions } from '@/hooks/use-permissions';

interface Props extends CardProps {
  folder: IFolderManager;
  selected?: boolean;
  onSelect?: VoidFunction;
  availableFolders?: { name: string; path: string }[];
  onDelete: VoidFunction;
  onToggleFavorite: (uniqueId: string, isFavorited: boolean) => Promise<boolean>;
  onRefresh?: VoidFunction;
  getFileFormat: (fileName: string) => string;
  sx?: object;
}

export default function FileManagerFolderItem({
  folder,
  selected,
  onSelect,
  availableFolders,
  onDelete,
  onToggleFavorite,
  onRefresh,
  sx,
  ...other
}: Props) {
  const { enqueueSnackbar } = useSnackbar();
  const { copy } = useCopyToClipboard();
  
  const [inviteEmail, setInviteEmail] = useState('');
  const [folderName, setFolderName] = useState(folder.name);
  const { loading, canRead, canWrite } = usePermissions(Number(folder.id));
  const rename = useBoolean();
  const moveFolder = useBoolean();
  const checkbox = useBoolean();
  const share = useBoolean();
  const popover = usePopover();
  const confirm = useBoolean();
  const details = useBoolean();
  const favorite = useBoolean(folder.isFavorited);

  const handleChangeInvite = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    setInviteEmail(event.target.value);
  }, []);

  const handleChangeFolderName = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    setFolderName(event.target.value);
  }, []);

  const handleCopy = useCallback(async () => {
    try {
      const shareLink = await fileManagerApi.generateShareLink(folder.uniqueId);
      await copy(shareLink);
      enqueueSnackbar('Link copied to clipboard!', { variant: 'success' });
    } catch (error) {
      console.error('Error generating share link:', error);
      enqueueSnackbar('Error generating share link', { variant: 'error' });
    }
  }, [folder.uniqueId, copy, enqueueSnackbar]);

  const handleRename = useCallback(async () => {
    try {
      await fileManagerApi.renameDocument(folder.uniqueId, folderName);
      rename.onFalse();
      enqueueSnackbar('Folder renamed successfully');
      if (onRefresh) {
        onRefresh();
      }
    } catch (error) {
      console.error('Error renaming folder:', error);
      enqueueSnackbar('Error renaming folder', { variant: 'error' });
    }
  }, [folder.uniqueId, folderName, rename, enqueueSnackbar, onRefresh]);

  const handleToggleFavorite = useCallback(async () => {
    try {
      await onToggleFavorite(folder.uniqueId, favorite.value);
      favorite.onToggle();
    } catch (error) {
      console.error('Error toggling favorite:', error);
      enqueueSnackbar('Error updating favorite status', { variant: 'error' });
    }
  }, [folder.uniqueId, favorite.value, onToggleFavorite, enqueueSnackbar]);
  const handleDownload = useCallback(async () => {
    try {
      await fileManagerApi.downloadElement(folder.uniqueId, folder.name);
      enqueueSnackbar('Download started successfully', { variant: 'success' });
    } catch (error) {
      console.error('Error downloading folder:', error);
      enqueueSnackbar('Error downloading folder', { variant: 'error' });
    }
  }, [folder.uniqueId, folder.name, enqueueSnackbar]);

  const renderAction = (
    <Stack
      direction="row"
      alignItems="center"
      sx={{
        top: 8,
        right: 8,
        position: 'absolute',
      }}
    >
      <Checkbox
        color="warning"
        icon={<Iconify icon="eva:star-outline" />}
        checkedIcon={<Iconify icon="eva:star-fill" />}
        checked={favorite.value}
        onChange={handleToggleFavorite}
      />

      <IconButton color={popover.open ? 'inherit' : 'default'} onClick={popover.onOpen}>
        <Iconify icon="eva:more-vertical-fill" />
      </IconButton>
    </Stack>
  );

  const renderIcon = (checkbox.value || selected) && onSelect ? (
    <Checkbox
      size="medium"
      checked={selected}
      onClick={onSelect}
      icon={<Iconify icon="eva:radio-button-off-fill" />}
      checkedIcon={<Iconify icon="eva:checkmark-circle-2-fill" />}
      sx={{ p: 0.75 }}
    />
  ) : (
    <Box component="img" src="/assets/icons/files/ic_folder.svg" sx={{ width: 36, height: 36 }} />
  );
  const renderText = (
    <Stack spacing={0.5}>
      <ListItemText
        primary={folder.name}
        secondary={
          <>
            {folder.size || 0} files
          </>
        }
        primaryTypographyProps={{
          noWrap: true,
          typography: 'subtitle1',
        }}
        secondaryTypographyProps={{
          component: 'span',
          alignItems: 'center',
          typography: 'caption',
          color: 'text.disabled',
          display: 'inline-flex',
        }}
      />

      <Stack
        direction="row"
        alignItems="center"
        sx={{
          typography: 'caption',
          color: 'text.disabled',
        }}
      >
        <Box component="span">
          {fDateTime(folder.modifiedAt || folder.createdAt || new Date())}
        </Box>
      </Stack>
    </Stack>
  );
  return (
    <>
      <Stack
        component={Paper}
        variant="outlined"
        spacing={1}
        alignItems="flex-start"
        sx={{
          p: 2.5,
          borderRadius: 2,
          bgcolor: 'unset',
          cursor: 'pointer',
          position: 'relative',
          ...((checkbox.value || selected) && {
            bgcolor: 'background.paper',
            boxShadow: (theme) => theme.customShadows.z20,
          }),
          ...sx,
        }}
        {...other}
      >
        <Box onMouseEnter={checkbox.onTrue} onMouseLeave={checkbox.onFalse}>
          {renderIcon}
        </Box>

        {renderAction}
        {renderText}
      </Stack>

      <CustomPopover
        open={popover.open}
        onClose={popover.onClose}
        arrow="right-top"
        sx={{ width: 160 }}
      >
        {/* Actions en lecture seule - toujours visibles */}
        <MenuItem onClick={() => {
          popover.onClose();
          details.onTrue();
        }}>
          <Iconify icon="ph:folder-open" />
          Open folder
        </MenuItem>

        <MenuItem onClick={() => {
          popover.onClose();
          handleDownload();
        }}>
          <Iconify icon="material-symbols:download" />
          Download
        </MenuItem>

        <MenuItem onClick={() => {
          popover.onClose();
          handleCopy();
        }}>
          <Iconify icon="eva:link-2-fill" />
          Copy Link
        </MenuItem>
        <MenuItem onClick={() => {
              popover.onClose();
              share.onTrue();
            }}>
              <Iconify icon="solar:share-bold" />
              Share
            </MenuItem>
        {/* Actions nécessitant des permissions d'écriture */}
        {   canWrite && (
          <>
            <Divider sx={{ borderStyle: 'dashed' }} />

            <MenuItem onClick={() => {
              popover.onClose();
              rename.onTrue();
            }}>
              <Iconify icon="ic:round-drive-file-rename-outline" />
              Rename
            </MenuItem>

            <MenuItem onClick={() => {
              popover.onClose();
              moveFolder.onTrue();
            }}>
              <Iconify icon="material-symbols:drive-file-move-outline" />
              Move
            </MenuItem>

           

            <Divider sx={{ borderStyle: 'dashed' }} />

            <MenuItem
              onClick={() => {
                confirm.onTrue();
                popover.onClose();
              }}
              sx={{ color: 'error.main' }}
            >
              <Iconify icon="solar:trash-bin-trash-bold" />
              Delete
            </MenuItem>
          </>
        )}
      </CustomPopover>

      <FileManagerFileDetails
        item={folder}
        favorited={favorite.value}
        onFavorite={onToggleFavorite}
        onCopyLink={handleCopy}
        open={details.value}
        onClose={details.onFalse}
        onDelete={() => {
          details.onFalse();
          onDelete();
        }}
      />

      <FileManagerShareDialog
        open={share.value}
        shared={folder.shared}
        inviteEmail={inviteEmail}
        onChangeInvite={handleChangeInvite}
        onCopyLink={handleCopy}
        onClose={() => {
          share.onFalse();
          setInviteEmail('');
        }}
      />

      <FileManagerNewFolderDialog
        open={rename.value}
        onClose={rename.onFalse}
        title="Rename Folder"
        onCreate={handleRename}
        folderName={folderName}
        onChangeFolderName={handleChangeFolderName}
      />

      <MoveDialog 
        open={moveFolder.value}
        onClose={moveFolder.onFalse}
        fileName={folder.name}
        folders={availableFolders?.filter(f => f.path !== folder.path)}
        folderName="File Manager"
        onRefresh={onRefresh}
      />

      <ConfirmDialog
        open={confirm.value}
        onClose={confirm.onFalse}
        title="Delete"
        content={`Are you sure want to delete ${folder.name}?`}
        action={
          <Button variant="contained" color="error" onClick={onDelete}>
            Delete
          </Button>
        }
      />
    </>
  );
}