import React, { useRef, useState } from 'react';
import { Button } from './Button';

interface FileUploaderProps {
    onUpload: (files: File[]) => void;
    multiple?: boolean;
    accept?: string;
    label?: string;
}

export const FileUploader: React.FC<FileUploaderProps> = ({
    onUpload,
    multiple = false,
    accept,
    label = 'Upload Files',
}) => {
    const inputRef = useRef<HTMLInputElement>(null);
    const [dragActive, setDragActive] = useState(false);

    const handleDrag = (e: React.DragEvent) => {
        e.preventDefault();
        e.stopPropagation();
        if (e.type === 'dragenter' || e.type === 'dragover') {
            setDragActive(true);
        } else if (e.type === 'dragleave') {
            setDragActive(false);
        }
    };

    const handleDrop = (e: React.DragEvent) => {
        e.preventDefault();
        e.stopPropagation();
        setDragActive(false);
        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            onUpload(Array.from(e.dataTransfer.files));
        }
    };

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        e.preventDefault();
        if (e.target.files && e.target.files.length > 0) {
            onUpload(Array.from(e.target.files));
        }
    };

    return (
        <div className="w-full">
            <div
                className={`relative flex flex-col items-center justify-center rounded-lg border-2 border-dashed p-6 transition-colors ${dragActive
                        ? 'border-primary-500 bg-primary-50'
                        : 'border-slate-300 bg-slate-50 hover:bg-slate-100'
                    }`}
                onDragEnter={handleDrag}
                onDragLeave={handleDrag}
                onDragOver={handleDrag}
                onDrop={handleDrop}
            >
                <input
                    ref={inputRef}
                    type="file"
                    className="hidden"
                    multiple={multiple}
                    accept={accept}
                    onChange={handleChange}
                />
                <div className="text-center">
                    <p className="mb-2 text-sm text-slate-600">
                        <span className="font-semibold">{label}</span>
                    </p>
                    <p className="text-xs text-slate-500">Drag and drop or click to select</p>
                </div>
                <Button
                    variant="outline"
                    size="sm"
                    className="mt-4"
                    onClick={() => inputRef.current?.click()}
                >
                    Select Files
                </Button>
            </div>
        </div>
    );
};
