import { useState, useCallback, useEffect, useMemo } from 'react';

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 IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import ListItemText from '@mui/material/ListItemText';
import { alpha, useTheme } from '@mui/material/styles';
import TableRow, { tableRowClasses } from '@mui/material/TableRow';
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
import { useBoolean } from '@/hooks/use-boolean';
import { useDoubleClick } from '@/hooks/use-double-click';
import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard';
import { usePathname } from 'next/navigation';
import { fData } from '@/utils/format-number';
import { fDate, fTime } from '@/utils/format-time';

import Iconify from '@/shared/components/iconify';
import { useSnackbar } from '@/shared/components/snackbar';
import FileThumbnail from '@/shared/components/file-thumbnail';
import { ConfirmDialog } from '@/shared/components/custom-dialog';
import CustomPopover, { usePopover } from '@/shared/components/custom-popover';

import { IFileManager, SourceDocument } 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 ImagePlayer from '@/shared/components/players/image-player';
import VideoPlayer from '@/shared/components/players/video-player';
import AudioPlayer from '@/shared/components/players/audio-player';
import DocPlayer from '@/shared/components/players/doc-player';
import { AccessLevel, fileManagerApi } from '@/shared/api/file-manager';
import { useDocuments } from '@/hooks/use-list-document';
import { useMoveDocument } from '@/hooks/use-move-document';
import { usePermissions } from '@/hooks/use-permissions';
import FileViewer from './file-viewer';
import ConditionalComponent from '@/shared/components/ConditionalComponent';


type Props = {
  row: IFileManager;
  selected: boolean;
  section: 'PERSONAL' | 'SHARED' | 'SHARED_WITH_ME';
  onToggleFavorite: (uniqueId: string, isFavorited: boolean) => Promise<boolean>;
  onSelectRow: VoidFunction;
  onDeleteRow: VoidFunction;
  onRefresh?: VoidFunction;
  availableFolders?: Array<{ name: string; path: string }>;
  onCreateCopy:(uniqueId: string, destinationPath: string) => Promise<void>;
  onOpenFolder?: (folderId: number, folderName: string) => void;
};

const canEdit = (permission: AccessLevel) => permission === AccessLevel.WRITE;

export default function FileManagerTableRow({
  row,
  selected,
  onSelectRow,
  onDeleteRow,
  onRefresh,
  onCreateCopy,
  onToggleFavorite,
  onOpenFolder,
availableFolders

}: Props) {

  const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'bmp', 'tiff', 'IMAGE'];
  const VIDEO_EXTENSIONS = ['mp4', 'webm', 'ogv', 'VIDEO'];
  const AUDIO_EXTENSIONS = ['mp3', 'wav', 'ogg', 'AUDIO'];
  const DOCUMENT_EXTENSIONS = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'DOCUMENT', 'PDF'];

  const theme = useTheme();
  const { enqueueSnackbar } = useSnackbar();
  const { copy } = useCopyToClipboard();
  const currentPath = usePathname();

  const [inviteEmail, setInviteEmail] = useState('');
  const [documentName, setDocumentName] = useState(row.name);
  const favorite = useBoolean(row.isFavorited);
  const details = useBoolean();
  const share = useBoolean();
  const confirm = useBoolean();
  const popover = usePopover();
  const edit = useBoolean();
  const file = useBoolean();
  const Movefile = useBoolean();

  const isFolder = row.type === 'folder';

const EXTENSIONS = ['IMAGE', 'VIDEO', 'AUDIO', 'PDF', 'DOCUMENT', 'JPG', 'JPEG', 'PNG', 'GIF', 'SVG', 'MP4', 'WEBM', 'OGV', 'MP3', 'WAV', 'OGG', 'DOC', 'DOCX'];
 

  const { moveDocument } = useMoveDocument(onRefresh);
  const { loading, canRead, canWrite } = usePermissions(Number(row.id));

  useEffect(() => {
    setDocumentName(row.name);
  }, [row.name]);
  const handleOpenFolder = useCallback(() => {
    if (isFolder && onOpenFolder) {
      onOpenFolder(Number(row.id), row.name);
      popover.onClose();
    }
  }, [isFolder, row.id, row.name, onOpenFolder, popover]);

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

  const handleChangeDocumentName = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    setDocumentName(event.target.value);
  }, []);
  
  const handleShare = useCallback(async (email: string, accessLevel: AccessLevel) => {
    try {
      await fileManagerApi.shareDocument(row.uniqueId, email, accessLevel);
      enqueueSnackbar('Document shared successfully');
      share.onFalse();
      if (onRefresh) {
        onRefresh();
      }
    } catch (error) {
      console.error('Error sharing document:', error);
      enqueueSnackbar('Error sharing document', { variant: 'error' });
    }
  }, [row.uniqueId, enqueueSnackbar, share, onRefresh]);

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

  const handleRename = useCallback(async () => {
    try {
      await fileManagerApi.renameDocument(row.uniqueId, documentName);
      edit.onFalse();
      enqueueSnackbar('Document renamed successfully');
      if (onRefresh) {
        onRefresh();
      }
      setDocumentName(documentName); 
    } catch (error) {
      console.error(error);
      enqueueSnackbar('Error renaming document', { variant: 'error' });
    }
  }, [row.uniqueId, documentName, edit, enqueueSnackbar, onRefresh]);

  const handleMove = useCallback(async (destinationFolderPath: string) => {
    const destinationFolder = availableFolders?.find(folder =>
      folder.path.trim().toLowerCase() === destinationFolderPath.trim().toLowerCase()
    );

    if (!destinationFolder) {
      enqueueSnackbar('Destination folder not found', { variant: 'error' });
      return;
    }
    const sourceDocument: SourceDocument = {
      path: row.path?.replace(/\//g, '\\').trim() || null, 
      type: row.type,
      name: row.name,
      url: row.url || null,
    };

    try {
      const success = await moveDocument(sourceDocument, {
        path: destinationFolder.path.replace(/\//g, '\\').trim(), 
        name: destinationFolder.name,
      });

      if (success) {
        Movefile.onFalse();
        enqueueSnackbar('Document moved successfully');
      }
    } catch (error) {
      enqueueSnackbar('Error moving document', { variant: 'error' });
    }
  }, [moveDocument, row, availableFolders, Movefile, enqueueSnackbar]);

  const handleCreateCopy = useCallback(async () => {
    try {
      const destinationPath = row.path;
      
      if (!destinationPath) {
        throw new Error('Destination path is undefined');
      }
  
      await onCreateCopy(row.uniqueId, destinationPath);
      enqueueSnackbar('Copy created successfully', { variant: 'success' });
  
      if (onRefresh) {
        onRefresh();
      }
    } catch (error) {
      console.error('Error creating copy:', error);
      enqueueSnackbar('Error creating copy', { variant: 'error' });
    }
  }, [row.uniqueId, row.path, onCreateCopy, enqueueSnackbar, onRefresh]);

  const handleToggleFavorite = useCallback(async (
    event: React.ChangeEvent<HTMLInputElement>,
    checked: boolean
  ) => {
    event.stopPropagation();
    try {
      const success = await onToggleFavorite(row.uniqueId, favorite.value);
      
      if (success) {
        favorite.onToggle();
        enqueueSnackbar(
          !favorite.value ? 'Added to favorites' : 'Removed from favorites',
          { variant: 'success' }
        );
      }
    } catch (error) {
      console.error('Error toggling favorite:', error);
      enqueueSnackbar('Error updating favorite status', { variant: 'error' });
    }
  }, [row.uniqueId, favorite.value, onToggleFavorite, enqueueSnackbar]);

  const handleDownload = useCallback(async () => {
    try {
      await fileManagerApi.downloadElement(row.uniqueId,row.name);
      enqueueSnackbar('Download started successfully', { variant: 'success' });
    } catch (error) {
      console.error('Error downloading file:', error);
      enqueueSnackbar('Error downloading file', { variant: 'error' });
    }
  }, [row.uniqueId, enqueueSnackbar]);
  const handleDelete = useCallback(async () => {
    confirm.onTrue();
  }, [confirm]);

  const formatDate = (date: string | null | undefined) => {
    if (!date) {
      return {
        date: 'N/A',
        time: 'N/A'
      };
    }
    return {
      date: fDate(date),
      time: fTime(date)
    };
  };

  const createdDateFormatted = formatDate(row.createdAt);
  const modifiedDateFormatted = formatDate(row.modifiedAt);

  

  const getFileFormat = (fileName: string): string => {
    if (!fileName) return '';
    if (fileName === 'folder') return 'folder';
    const extension = fileName.split('.').pop()?.toLowerCase() || '';
    const typeMap: { [key: string]: string } = {
      pdf: 'pdf',
      doc: 'word',
      docx: 'word',
      xls: 'excel',
      xlsx: 'excel',
      ppt: 'ppt',
      pptx: 'ppt',
      txt: 'txt',
      jpg: 'jpg',
      jpeg: 'jpg',
      png: 'png',
      gif: 'gif',
      svg: 'svg',
      mp3: 'audio',
      wav: 'audio',
      mp4: 'video',
      avi: 'video',
      mov: 'video',
      zip: 'zip',
      rar: 'zip',
      ai: 'ai',
      psd: 'psd',
      esp: 'esp',
    };
  
    return typeMap[extension] || 'file';
  };
  
  const handleOpenFile = useCallback(async () => {
    try {
      const url = await fileManagerApi.getFileUrl(row.path);
      if (url) {
    
        row.url = url;
        file.onTrue();
      }
    } catch (error) {
      console.error('Error opening file:', error);
      enqueueSnackbar('Error opening file', { variant: 'error' });
    }
  }, [row.uniqueId, file, enqueueSnackbar]);

  return (
    <>
      <TableRow
        selected={selected}
        sx={{
          borderRadius: 2,
          [`&.${tableRowClasses.selected}, &:hover`]: {
            backgroundColor: 'background.paper',
            boxShadow: theme.customShadows.z20,
            transition: theme.transitions.create(['background-color', 'box-shadow'], {
              duration: theme.transitions.duration.shortest,
            }),
            '&:hover': {
              backgroundColor: 'background.paper',
              boxShadow: theme.customShadows.z20,
            },
          },
          [`& .${tableCellClasses.root}`]: {
            borderTop: `solid 1px ${alpha(theme.palette.grey[500], 0.16)}`,
            borderBottom: `solid 1px ${alpha(theme.palette.grey[500], 0.16)}`,
            '&:first-of-type': {
              borderTopLeftRadius: 16,
              borderBottomLeftRadius: 16,
              borderLeft: `solid 1px ${alpha(theme.palette.grey[500], 0.16)}`,
            },
            '&:last-of-type': {
              borderTopRightRadius: 16,
              borderBottomRightRadius: 16,
              borderRight: `solid 1px ${alpha(theme.palette.grey[500], 0.16)}`,
            },
          },
        }}
      >
        <TableCell padding="checkbox">
          <Checkbox
            checked={selected}
            onClick={onSelectRow}
          />
        </TableCell>

        <TableCell>
          <Stack direction="row" alignItems="center" spacing={2}>
            <FileThumbnail 
              file={isFolder ? 'folder' : getFileFormat(row.name)} 
              sx={{ width: 36, height: 36 }} 
            />
            <Typography
              noWrap
              variant="inherit"
              sx={{
                maxWidth: 360,
                cursor: 'pointer',
                ...(details.value && { fontWeight: 'fontWeightBold' }),
              }}
            >
              {row.name}
            </Typography>
          </Stack>
        </TableCell>

        <TableCell sx={{ whiteSpace: 'nowrap' }}>
          {isFolder 
            ? `${row.size || 0} files` 
            : row.size 
              ? fData(row.size) 
              : 'N/A'}
        </TableCell>

        <TableCell sx={{ whiteSpace: 'nowrap' }}>
          {row.type}
        </TableCell>

        <TableCell sx={{ whiteSpace: 'nowrap' }}>
          <ListItemText
            primary={createdDateFormatted.date}
            secondary={createdDateFormatted.time}
            primaryTypographyProps={{ typography: 'body2' }}
            secondaryTypographyProps={{
              mt: 0.5,
              component: 'span',
              typography: 'caption',
            }}
          />
        </TableCell>

        <TableCell sx={{ whiteSpace: 'nowrap' }}>
          <ListItemText
            primary={modifiedDateFormatted.date}
            secondary={modifiedDateFormatted.time}
            primaryTypographyProps={{ typography: 'body2' }}
            secondaryTypographyProps={{
              mt: 0.5,
              component: 'span',
              typography: 'caption',
            }}
          />
        </TableCell>

        <TableCell align="left" sx={{ whiteSpace: 'nowrap' }}>
          {row.ownerFullName && (
            <Stack direction='row' spacing={1}>
              <Avatar sx={{ width: 24, height: 24 }}>
                {row.ownerFullName?.split(' ')[0]?.[0] || 'U'}
              </Avatar>
              {row.ownerFullName || 'Unknown User'}
            </Stack>
          )}
        </TableCell>

        <TableCell
          align="right"
          sx={{
            px: 1,
            whiteSpace: 'nowrap',
          }}
        >
          <Checkbox
            color="warning"
            icon={<Iconify icon="eva:star-outline" />}
            checkedIcon={<Iconify icon="eva:star-fill" />}
            checked={row.isFavorited}
            onChange={handleToggleFavorite}
            sx={{ p: 0.75 }}
          />

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

      <CustomPopover
        open={popover.open}
        onClose={popover.onClose}
        arrow="right-top"
        sx={{ width: 160 }}
      >
        {/* Actions en lecture seule - toujours visibles */}
      
        {isFolder ? (
          <MenuItem onClick={handleOpenFolder}>
            <Iconify icon="ph:folder-open" />
            Open folder
          </MenuItem>
        ) : (
          EXTENSIONS.includes(row.type) && (
            <MenuItem onClick={() => {
              popover.onClose();
               handleOpenFile();
            }}>
              <Iconify icon="material-symbols:file-open-outline" />
              Open file
            </MenuItem>
          )
        )}

        <MenuItem onClick={() => {
          popover.onClose();
          details.onTrue();
        }}>
          <Iconify icon="bi:info-circle" />
          Details
        </MenuItem>

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

            <MenuItem onClick={() => {
              popover.onClose();
              handleCreateCopy();
            }}>
              <Iconify icon="foundation:page-copy" />
              Create copy
            </MenuItem>

            

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

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

      <MoveDialog 
        open={Movefile.value}
        onClose={Movefile.onFalse}
        fileName={row.name}
        folderName={isFolder ? row.name : 'File Manager'}
        folders={availableFolders?.filter(f => f.path !== row.path)}
        onMove={handleMove}
        onRefresh={onRefresh}
      />

      <FileManagerNewFolderDialog
        open={edit.value}
        onClose={edit.onFalse}
        title={isFolder ? 'Rename Folder' : 'Rename File'}
        onPaste={() => {
          edit.onFalse();
          setDocumentName(documentName);
        }}
        folderName={documentName}
        onChangeFolderName={handleChangeDocumentName}
        onCreate={handleRename}
      />

      <FileManagerFileDetails
        item={row}
        favorited={favorite.value}
        onFavorite={onToggleFavorite}
        onCopyLink={handleCopy}
        open={details.value}
        onClose={details.onFalse}
        onDelete={onDeleteRow}
        onRefresh={onRefresh}
      />

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

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

{file.value && row.url && (
  <>
    <ConditionalComponent isValid={IMAGE_EXTENSIONS.includes(row.type)}>
      <ImagePlayer
        type={row.type}
        url={row.url}
        open={file.value}
        onClose={file.onFalse}
        title={row.name}
      />
    </ConditionalComponent>
    
    <ConditionalComponent isValid={VIDEO_EXTENSIONS.includes(row.type)}>
      <VideoPlayer
        type={row.type}
        url={row.url}
        open={file.value}
        onClose={file.onFalse}
      />
    </ConditionalComponent>
    
    <ConditionalComponent isValid={AUDIO_EXTENSIONS.includes(row.type)}>
      <AudioPlayer
        type={row.type}
        url={row.url}
        open={file.value}
        onClose={file.onFalse}
      />
    </ConditionalComponent>
    
    <ConditionalComponent isValid={DOCUMENT_EXTENSIONS.includes(row.type)}>
      <DocPlayer
        type={row.type}
        url={row.url}
        open={file.value}
        onClose={file.onFalse}
      />
    </ConditionalComponent>
  </>
)}
    </>
  );
}