import React, { useCallback, useState, useEffect } from 'react';
import { useDropzone } from 'react-dropzone';
import { Label } from '../ui/label';
import { FolderInput, Trash2 } from 'lucide-react';

interface FileWithPreview extends File {
  preview: string;
}

interface InitialFileState {
  file: FileWithPreview | null;
  path: string | null;
}

interface DropZonePropsInterface {
  title?: string;
  handleFileChange: (key: string, file: File | null) => void;
  name: string;
  initialItem?: File | string | null;
  currentFile?: File | null;  // Add this prop
}

const DropZone: React.FC<DropZonePropsInterface> = ({
  title = 'Upload File',
  handleFileChange,
  name,
  initialItem = null,
  currentFile = null,  // Add this prop
}) => {
  const [fileState, setFileState] = useState<InitialFileState>({
    file: null,
    path: typeof initialItem === 'string' ? initialItem : null
  });

  // Effect to handle initial setup and updates
  useEffect(() => {
    if (currentFile) {
      // If there's a current file in form state, create preview
      const fileWithPreview = Object.assign(currentFile, {
        preview: URL.createObjectURL(currentFile)
      }) as FileWithPreview;
      setFileState({ file: fileWithPreview, path: null });
    } else if (initialItem && typeof initialItem === 'string') {
      // Handle path-based initialItem
      setFileState(prev => ({ ...prev, path: initialItem }));
    } else if (initialItem instanceof File) {
      // Handle File-based initialItem
      const fileWithPreview = Object.assign(initialItem, {
        preview: URL.createObjectURL(initialItem)
      }) as FileWithPreview;
      setFileState({ file: fileWithPreview, path: null });
    } else if (!initialItem && !currentFile) {
      // Reset state if no file
      setFileState({ file: null, path: null });
    }
  }, [initialItem, currentFile]);

  const onDrop = useCallback(
    (acceptedFiles: File[]) => {
      if (acceptedFiles.length > 0) {
        const fileWithPreview = Object.assign(acceptedFiles[0], {
          preview: URL.createObjectURL(acceptedFiles[0]),
        }) as FileWithPreview;
        
        setFileState({ file: fileWithPreview, path: null });
        handleFileChange(name, fileWithPreview);
      }
    },
    [name, handleFileChange]
  );

  const removeFile = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    setFileState({ file: null, path: null });
    handleFileChange(name, null);
  }, [name, handleFileChange]);

  const { getRootProps, getInputProps } = useDropzone({
    onDrop,
    accept: {
      'image/jpeg': ['.jpeg', '.jpg'],
      'image/png': ['.png'],
      'application/pdf': ['.pdf'],
      'application/msword': ['.doc', '.docx']
    },
    multiple: false
  });

  const renderPreview = () => {
    const currentFile = fileState.file;
    const currentPath = fileState.path;

    if (currentFile) {
      if (currentFile.type.startsWith('image/')) {
        return (
          <div className="mt-4 flex flex-col items-center gap-2">
            <img
              src={currentFile.preview}
              alt={currentFile.name}
              className="max-h-32 border rounded"
            />
            <div className="flex items-center gap-2">
              <FolderInput className="w-4 h-4" />
              <span className="text-sm">{currentFile.name}</span>
              <button
                type="button"
                onClick={removeFile}
                className="hover:bg-gray-200 p-1 rounded-full"
                aria-label="Remove file"
              >
                <Trash2 className="w-4 h-4 text-red-500" />
              </button>
            </div>
          </div>
        );
      }
    } else if (currentPath) {
      if (currentPath.match(/\.(jpg|jpeg|png)$/i)) {
        return (
          <div className="mt-4 flex flex-col items-center gap-2">
            <img
              src={currentPath}
              alt="Uploaded file"
              className="max-h-32 border rounded"
            />
            <div className="flex items-center gap-2">
              <FolderInput className="w-4 h-4" />
              <span className="text-sm">{currentPath.split('/').pop()}</span>
              <button
                type="button"
                onClick={removeFile}
                className="hover:bg-gray-200 p-1 rounded-full"
                aria-label="Remove file"
              >
                <Trash2 className="w-4 h-4 text-red-500" />
              </button>
            </div>
          </div>
        );
      }
    }

    return null;
  };

  // Cleanup preview URLs on unmount
  useEffect(() => {
    return () => {
      if (fileState.file?.preview) {
        URL.revokeObjectURL(fileState.file.preview);
      }
    };
  }, [fileState.file]);

  return (
    <div className="flex flex-col gap-4">
      <Label>{title}</Label>
      <div
        {...getRootProps()}
        className="bg-sky-50 dark:bg-background border-gray-400 border border-dashed px-4 py-8 rounded cursor-pointer"
      >
        <input {...getInputProps()} />
        <div className="text-center">
          <p className="text-sm">Drag and drop a file here, or click to select a file</p>
          <em className="text-sm block mt-1">(*.jpeg, *.png, *.pdf, *.doc files accepted)</em>
        </div>
        
        {renderPreview()}
      </div>
    </div>
  );
};

export default DropZone;