import * as React from "react"
import { cn } from "@/lib/utils"
import { Upload } from "lucide-react"

export interface FileInputProps
  extends React.InputHTMLAttributes<HTMLInputElement> {
  onFileChange?: (file: File | null) => void;
}

const FileInput = React.forwardRef<HTMLInputElement, FileInputProps>(
  ({ className, onFileChange, ...props }, ref) => {
    const [fileName, setFileName] = React.useState<string | null>(null);
    const fileInputRef = React.useRef<HTMLInputElement>(null);

    const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
      const file = event.target.files ? event.target.files[0] : null;
      setFileName(file?.name || null);
      if (onFileChange) {
        onFileChange(file);
      }
    };

    const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => {
      event.preventDefault();
      event.stopPropagation();
    };

    const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
      event.preventDefault();
      event.stopPropagation();
      
      const file = event.dataTransfer.files[0];
      if (file && fileInputRef.current) {
        // Create a DataTransfer object to set the file to the input
        const dataTransfer = new DataTransfer();
        dataTransfer.items.add(file);
        fileInputRef.current.files = dataTransfer.files;
        
        setFileName(file.name);
        if (onFileChange) {
          onFileChange(file);
        }
      }
    };

    return (
      <div
        className={cn(
          "mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md",
          className
        )}
        onDragOver={handleDragOver}
        onDrop={handleDrop}
      >
        <div className="space-y-1 text-center">
          {fileName ? (
            <div className="flex flex-col items-center">
              <div className="text-sm text-gray-600 mb-2">Selected file: {fileName}</div>
              <button
                type="button"
                className="text-sm text-red-500 hover:text-red-700"
                onClick={() => {
                  setFileName(null);
                  if (fileInputRef.current) {
                    fileInputRef.current.value = '';
                  }
                  if (onFileChange) {
                    onFileChange(null);
                  }
                }}
              >
                Remove
              </button>
            </div>
          ) : (
            <>
              <Upload className="mx-auto h-12 w-12 text-gray-400" />
              <div className="flex text-sm text-gray-600">
                <label
                  htmlFor={props.id}
                  className="relative cursor-pointer bg-white rounded-md font-medium text-[#3B82F6] hover:text-[#1E40AF] focus-within:outline-none"
                >
                  <span>Upload a file</span>
                  <input
                    id={props.id}
                    ref={(input) => {
                      if (input) {
                        // @ts-ignore - ref is not recognized as a valid prop
                        if (typeof ref === 'function') ref(input);
                        else if (ref) ref.current = input;
                        fileInputRef.current = input;
                      }
                    }}
                    type="file"
                    className="sr-only"
                    onChange={handleFileChange}
                    {...props}
                  />
                </label>
                <p className="pl-1">or drag and drop</p>
              </div>
              <p className="text-xs text-gray-500">
                {props.accept === '.csv' ? 'CSV up to 10MB' : 'File up to 10MB'}
              </p>
            </>
          )}
        </div>
      </div>
    )
  }
)

FileInput.displayName = "FileInput"

export { FileInput }
