import { useState } from 'react';
import Button from '@mui/material/Button';
import DialogTitle from '@mui/material/DialogTitle';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import Dialog, { DialogProps } from '@mui/material/Dialog';
import Iconify from '@/shared/components/iconify';
import { Box, Divider, Grid, IconButton, Tooltip } from '@mui/material';
import { useSnackbar } from '@/shared/components/snackbar';

// ----------------------------------------------------------------------

interface Props extends DialogProps {
  title?: string;
  fileName?: string;
  folderName?: string;
  folders?: { name: string; path: string }[]; 
  onMove?: (destinationPath: string) => Promise<void>;
  open: boolean;
  onClose: VoidFunction;
  onRefresh?: VoidFunction;
}

export default function MoveDialog({
  title = 'Move " ',
  open,
  folders = [],
  onClose,
  folderName,
  fileName,
  onMove,
  onRefresh,
  ...other
}: Props) {
  const { enqueueSnackbar } = useSnackbar();
  const [clickedIndex, setClickedIndex] = useState<number | null>(null);
  const [hoveredBoxes, setHoveredBoxes] = useState(new Array(folders.length).fill(false));

  const handleMoveAction = async (destinationFolderPath: string) => {
    try {
      if (destinationFolderPath === folderName) {
        enqueueSnackbar('Cannot move to the same folder', { variant: 'error' });
        return;
      }
      

      if (onMove) {
        await onMove(destinationFolderPath);
        if (onRefresh) {
          onRefresh();
        }
        onClose();
      }
    } catch (error) {
      console.error('Error moving document:', error);
      enqueueSnackbar('Error moving document', { variant: 'error' });
    }
  };

  function renderHoverActions(folder: { name: string; path: string }) {
    return (
      <>
        <Button
          sx={{ color: 'Highlight', padding: '0' }}
          onClick={() => handleMoveAction(folder.path)}
        >
          Move
        </Button>
        <Tooltip title="Show content">
          <IconButton sx={{ padding: '0' }}>
            <Iconify
              icon="iconamoon:arrow-right-2-bold"
              sx={{ color: 'Highlight', height: '15px', width: '15px' }}
            />
          </IconButton>
        </Tooltip>
      </>
    );
  }

  const handleHover = (index: number, isHovered: boolean) => {
    const updatedHoveredBoxes = [...hoveredBoxes];
    updatedHoveredBoxes[index] = isHovered;
    setHoveredBoxes(updatedHoveredBoxes);
  };

  return (
    <Dialog fullWidth maxWidth="sm" open={open} onClose={onClose} {...other}>
      <DialogTitle sx={{ p: (theme) => theme.spacing(3, 3, 3, 3) }}>
        {title + fileName + ' "'}
      </DialogTitle>

      <Divider />

      <Box sx={{ p: (theme) => theme.spacing(2, 2, 2, 2), backgroundColor: 'inherit' }}>
        Current location:
        <Button
          variant="outlined"
          sx={{ m: (theme) => theme.spacing(0, 0, 0, 1) }}
        >
          <Iconify
            icon="flat-color-icons:folder"
            sx={{ marginRight: '4px', marginLeft: '0px' }}
          />
          {folderName}
        </Button>
      </Box>

      <Divider />

      <DialogContent dividers sx={{ pt: 1, pb: 0, border: 'none' }}>
        <Box
          sx={{
            p: (theme) => theme.spacing(2, 2, 2, 2),
            borderRadius: '10px',
            backgroundColor: 'inherit',
            mb: 1,
            display: 'flex',
            alignItems: 'center',
            width: '100%',
          }}
        >
          <Grid container direction="column">
            {folders
              .filter(folder => folder.name !== folderName) // Updated to handle objects
              .map((folder, index) => (
                <Box
                  key={index}
                  sx={{
                    '&:hover': {
                      backgroundColor: 'inherit',
                      border:
                        clickedIndex === index
                          ? '1px dashed #9E9E9E'
                          : '1px dashed #9E9E9E',
                      borderRadius: '10px',
                    },
                    p: (theme) => theme.spacing(2, 0, 2, 1),
                    border: clickedIndex === index ? '1px dashed #9E9E9E' : 'none',
                    borderRadius: clickedIndex === index ? '10px' : '0',
                  }}
                  onMouseEnter={() => handleHover(index, true)}
                  onMouseLeave={() => handleHover(index, false)}
                  onClick={() => setClickedIndex(index)}
                >
                  <Grid container direction="row" alignItems="center">
                    <Grid
                      item
                      sx={{
                        display: 'flex',
                        alignItems: 'center',
                        marginRight: '10px',
                      }}
                    >
                      <Iconify icon="flat-color-icons:folder" sx={{ marginRight: '10px' }} />
                      {folder.name}
                    </Grid>
                    <Grid
                      item
                      sx={{
                        marginLeft: 'auto',
                        marginRight: '5px',
                        display: 'flex',
                        alignItems: 'center',
                      }}
                    >
                      {hoveredBoxes[index] && renderHoverActions(folder)}
                    </Grid>
                  </Grid>
                </Box>
              ))}
          </Grid>
        </Box>
      </DialogContent>

      <Divider />

      <DialogActions>
        <Button
          variant="contained"
          onClick={() => {
            if (clickedIndex !== null) {
              handleMoveAction(folders[clickedIndex].path); // Pass path
            }
          }}
          disabled={clickedIndex === null}
        >
          Move
        </Button>

        <Button variant="outlined" onClick={onClose}>
          Cancel
        </Button>
      </DialogActions>
    </Dialog>
  );
}
