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 MenuItem from '@mui/material/MenuItem';
import Checkbox from '@mui/material/Checkbox';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import { CardProps } from '@mui/material/Card';

import { useBoolean } from '@/hooks/use-boolean';
import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard';
import { useSnackbar } from '@/shared/components/snackbar';

import Iconify from '@/shared/components/iconify';
import FileThumbnail from '@/shared/components/file-thumbnail';
import TextMaxLine from '@/shared/components/text-max-line';
import { ConfirmDialog } from '@/shared/components/custom-dialog';
import CustomPopover, { usePopover } from '@/shared/components/custom-popover';

import { IFileManager } from '@/shared/types/file';
import { fileManagerApi } from '@/shared/api/file-manager';

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 { fData } from '@/utils/format-number';
import { fDateTime } from '@/utils/format-time';
import { Divider } from '@mui/material';
import VideoPlayer from '@/shared/components/players/video-player';
import AudioPlayer from '@/shared/components/players/audio-player';
import ImagePlayer from '@/shared/components/players/image-player';
import DocPlayer from '@/shared/components/players/doc-player';
import { getUserByEmail } from '@/shared/api/user';
import { usePermissions } from '@/hooks/use-permissions';



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

export default function FileManagerFileItem({
  file,
  selected,
  onSelect,
  onDelete,
  onToggleFavorite,
  availableFolders,
  onRefresh,
  getFileFormat,
  sx,
  ...other
}: Props) {
  const { enqueueSnackbar } = useSnackbar();
  const { copy } = useCopyToClipboard();
  const [inviteEmail, setInviteEmail] = useState('');
  const [fileName, setFileName] = useState(file.name);
  const { loading, canRead, canWrite } = usePermissions(Number(file.id));
  const EXTENSIONS = ['mp4', 'webm', 'ogv', 'gif', 'jpg', 'jpeg', 'svg', 'png', 'mp3', 'wav', 'ogg', 'pdf'];

  const fileView = useBoolean();
  const moveFile = useBoolean();
  const checkbox = useBoolean();
  const share = useBoolean();
  const confirm = useBoolean();
  const details = useBoolean();
  const favorite = useBoolean(file.isFavorited);
  const popover = usePopover();
  const rename = useBoolean();
  
  const handleChangeInvite = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    setInviteEmail(event.target.value);
  }, []);

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

  const handleCopy = useCallback(async () => {
    try {
      const shareLink = await fileManagerApi.generateShareLink(file.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' });
    }
  }, [file.uniqueId, copy, enqueueSnackbar]);

  const handleRename = useCallback(async () => {
    try {
      await fileManagerApi.renameDocument(file.uniqueId, fileName);
      rename.onFalse();
      enqueueSnackbar('File renamed successfully');
      if (onRefresh) {
        onRefresh();
      }
    } catch (error) {
      console.error('Error renaming file:', error);
      enqueueSnackbar('Error renaming file', { variant: 'error' });
    }
  }, [file.uniqueId, fileName, rename, enqueueSnackbar, onRefresh]);
  
  const handleDeleteItem = useCallback(async (id: string) => {
    try {
      const email = localStorage.getItem('email');
      if (!email) {
        throw new Error('No email found in localStorage');
      }
      const userData = await getUserByEmail(email);

      await fileManagerApi.deleteDocuments(Number(userData.id), [file.path]);
      enqueueSnackbar('File deleted successfully');
      onDelete();
      if (onRefresh) {
        onRefresh();
      }
    } catch (error) {
      console.error('Error deleting file:', error);
      enqueueSnackbar('Error deleting file', { variant: 'error' });
    }
  }, [file.path, onDelete, onRefresh, enqueueSnackbar]);
  const handleToggleFavorite = useCallback(async () => {
    try {
      await onToggleFavorite(file.uniqueId, favorite.value);
      favorite.onToggle();
    } catch (error) {
      console.error('Error toggling favorite:', error);
      enqueueSnackbar('Error updating favorite status', { variant: 'error' });
    }
  }, [file.uniqueId, favorite.value, onToggleFavorite, enqueueSnackbar]);

  const handleDownload = useCallback(async () => {
    try {
      await fileManagerApi.downloadElement(file.uniqueId, file.name);
      enqueueSnackbar('Download started successfully', { variant: 'success' });
    } catch (error) {
      console.error('Error downloading file:', error);
      enqueueSnackbar('Error downloading file', { variant: 'error' });
    }
  }, [file.uniqueId, file.name, enqueueSnackbar]);
  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 }}
    />
  ) : (
    <FileThumbnail 
      file={file.type === 'folder' ? 'folder' : getFileFormat(file.name)} 
      sx={{ width: 36, height: 36 }} 
    />
  );

  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 renderText = (
    <>
      <TextMaxLine
        persistent
        variant="subtitle2"
        onClick={details.onTrue}
        sx={{ width: 1, mt: 2, mb: 0.5 }}
      >
        {file.name}
      </TextMaxLine>

      <Stack
        direction="row"
        alignItems="center"
        sx={{
          maxWidth: 0.99,
          whiteSpace: 'nowrap',
          typography: 'caption',
          color: 'text.disabled',
        }}
      >
        {fData(file.size)}

        <Box
          component="span"
          sx={{
            mx: 0.75,
            width: 2,
            height: 2,
            flexShrink: 0,
            borderRadius: '50%',
            bgcolor: 'currentColor',
          }}
        />
        <Typography noWrap component="span" variant="caption">
          {fDateTime(file.modifiedAt)}
        </Typography>
      </Stack>
    </>
  );

  return (
    <>
      <Stack
        component={Paper}
        variant="outlined"
        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>

        {renderText}
        {renderAction}
      </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();
              moveFile.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={file}
        favorited={favorite.value}
        onFavorite={onToggleFavorite}
        onCopyLink={handleCopy}
        open={details.value}
        onClose={details.onFalse}
        onDelete={() => {
          details.onFalse();
        handleDeleteItem(file.id)
        }}
      />

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

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

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

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

    
      <ImagePlayer 
        open={fileView.value} 
        onClose={fileView.onFalse} 
        type={file.type} 
        url={file.url} 
        title={file.name}
      />
      <DocPlayer 
        open={fileView.value} 
        onClose={fileView.onFalse} 
        type={file.type} 
        url={file.url} 
      />
      <VideoPlayer 
        open={fileView.value} 
        onClose={fileView.onFalse} 
        type={file.type} 
        url={file.url} 
      />
      <AudioPlayer 
        open={fileView.value} 
        onClose={fileView.onFalse} 
        type={file.type} 
        url={file.url}
      />
    </>
  );
}