import { useState, useEffect, useCallback } from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
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 { useSnackbar } from '@/shared/components/snackbar';
import Iconify from '@/shared/components/iconify';
import { Upload } from '@/shared/components/upload';
import { fileManagerApi } from '@/shared/api/file-manager';

interface Props extends DialogProps {
  title?: string;
  onCreate?: (folderName: string) => void;
  onUpdate?: (folderName: string) => void;
  folderName?: string;
  onChangeFolderName?: (event: React.ChangeEvent<HTMLInputElement>) => void;
  open: boolean;
  onClose: VoidFunction;
  onSuccess?: VoidFunction;
  onRefresh?: VoidFunction;
  section?: 'personal' | 'shared' | 'sharedWithMe';
  folderId?: number | null;
}

export default function FileManagerNewFolderDialog({
  title = 'Upload Files',
  open,
  onClose,
  onCreate,
  onUpdate,
  folderName,
  onRefresh,
  onChangeFolderName,
  onSuccess,
  section = 'personal',
  folderId,
  ...other
}: Props) {
  const { enqueueSnackbar } = useSnackbar();
  const [files, setFiles] = useState<(File | string)[]>([]);
  const [uploading, setUploading] = useState(false);
  const [creating, setCreating] = useState(false);
  useEffect(() => {
    if (!open) {
      setFiles([]);
    }
  }, [open]);

  const handleDrop = useCallback(
    (acceptedFiles: File[]) => {
      const newFiles = acceptedFiles.map((file) =>
        Object.assign(file, {
          preview: URL.createObjectURL(file),
        })
      );

      setFiles([...files, ...newFiles]);
    },
    [files]
  );

  const handleUpload = async () => {
    if (!files.length) {
      enqueueSnackbar('Please select files to upload', { variant: 'error' });
      return;
    }

    setUploading(true);
    try {
      await Promise.all(
        files.map((file) => {
          if (file instanceof File) {
            return fileManagerApi.uploadFile({
              file,
              section: section || 'personal',
              folderId: folderId || null
            });
          }
          return Promise.resolve();
        })
      );
      
      enqueueSnackbar('Files uploaded successfully');
      onClose();
      if (onSuccess) {
        onSuccess();
      }
      if (onRefresh) {
        onRefresh();
      }
    } catch (error) {
      console.error('Upload error:', error);
      enqueueSnackbar('Error uploading files', { variant: 'error' });
    } finally {
      setUploading(false);
      setFiles([]);
    }
  };

  const handleRemoveFile = (inputFile: File | string) => {
    const filtered = files.filter((file) => file !== inputFile);
    setFiles(filtered);
  };

  const handleRemoveAllFiles = () => {
    setFiles([]);
  };

  const handleAction = async (event: React.MouseEvent) => {
    event.preventDefault();
    if (!folderName) return;

    setCreating(true); 
    try {
      if (onUpdate) {
        await onUpdate(folderName);
      } else if (onCreate) {
        await onCreate(folderName);
      }
    } catch (error) {
      console.error('Folder action error:', error);
      enqueueSnackbar('Error performing folder action', { variant: 'error' });
    } finally {
      setCreating(false); 
    }
  }
  return (
    <Dialog fullWidth maxWidth="sm" open={open} onClose={onClose} {...other}>
      <DialogTitle sx={{ p: (theme) => theme.spacing(3, 3, 2, 3) }}>{title}</DialogTitle>

      <DialogContent dividers sx={{ pt: 1, pb: 0, border: 'none' }}>
        {title === 'Upload Files' ? (
          <Upload 
            multiple 
            files={files} 
            onDrop={handleDrop} 
            onRemove={handleRemoveFile}
            disabled={uploading}
          />
        ) : (
          <TextField
            fullWidth
            label="Name"
            value={folderName}
            onChange={onChangeFolderName}
            sx={{ mb: 3 }}
            disabled={creating}
          />
        )}
      </DialogContent>

      <DialogActions>
        {title === 'Upload Files' ? (
          <>
            <Button
              variant="contained"
              startIcon={<Iconify icon="eva:cloud-upload-fill" />}
              onClick={handleUpload}
              disabled={!files.length || uploading}
            >
              {uploading ? 'Uploading...' : 'Upload'}
            </Button>
            
            <Button variant="outlined" onClick={onClose} disabled={uploading}>
              Cancel
            </Button>
            
            {!!files.length && (
              <Button 
                variant="outlined" 
                color="error" 
                onClick={handleRemoveAllFiles}
                disabled={uploading}
              >
                Remove all
              </Button>
            )}
          </>
        ) : (
          <Stack direction="row" justifyContent="flex-end" flexGrow={1} spacing={1}>
            <Button 
              variant="contained" 
              onClick={handleAction}
              disabled={!folderName || creating}
            > {creating ? 'Creating...' : title.includes('Rename') ? 'Rename' : 'Create'}
            </Button>
            <Button variant="outlined" onClick={onClose}>
              Cancel
            </Button>
          </Stack>
        )}
      </DialogActions>
    </Dialog>
  );
}