'use client'
import {DragEvent, ReactNode, useRef, useState} from "react";
import {ImagePlus} from "lucide-react";

interface ImageDropZoneProps {
    onFileSelect: (file: File) => void;
    accept?: string;
    label?: ReactNode;
}

const acceptedTypes: string[] = ['image/png', 'image/jpeg', 'image/webp'];

function ImageDropZone({onFileSelect, accept = "image/png, image/jpeg, image/webp", label}: ImageDropZoneProps) {
    const inputRef = useRef<HTMLInputElement | null>(null);
    const [isDragging, setIsDragging] = useState<boolean>(false);
    
    function handleDragOver(e: DragEvent<HTMLDivElement>): void {
        e.preventDefault();
        setIsDragging(true);
    }
    
    function handleDragLeave(e: DragEvent<HTMLDivElement>): void {
        e.preventDefault();
        setIsDragging(false);
    }
    
    function handleDrop(e: DragEvent<HTMLDivElement>): void {
        e.preventDefault();
        setIsDragging(false);
        const file: File | undefined = e.dataTransfer.files?.[0];
        if (file && acceptedTypes.includes(file.type)) {
            onFileSelect(file);
        }
    }
    
    function handleClick(): void {
        inputRef.current?.click();
    }
    
    function handleInputChange(e: React.ChangeEvent<HTMLInputElement>): void {
        const file: File | undefined = e.target.files?.[0];
        if (file) {
            onFileSelect(file);
        }
    }
    
    return (
        <div
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
            onClick={handleClick}
            className={`flex flex-col items-center justify-center gap-2 border-2 border-dashed rounded-lg p-6 cursor-pointer transition-colors
                ${isDragging
                ? 'border-primary bg-primary/10'
                : 'border-secondary bg-dark-background hover:bg-tertiary'
            }`}
        >
            <input
                ref={inputRef}
                type="file"
                accept={accept}
                onChange={handleInputChange}
                className="hidden"
            />
            <ImagePlus className="w-8 h-8 text-muted"/>
            {label && <span className="text-text-primary text-sm">{label}</span>}
        </div>
    );
}

export default ImageDropZone;
