"use client"

import { cn } from "@/lib/utils"
import { useCallback, useRef, useState } from "react"

export function FileDropzone({
  onFilesSelected,
}: {
  onFilesSelected: (files: File[]) => void
}) {
  const [isDragging, setIsDragging] = useState(false)
  const inputRef = useRef<HTMLInputElement | null>(null)

  const handleFiles = (files: FileList | null) => {
    if (files) {
      onFilesSelected(Array.from(files))
    }
  }

  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault()
    setIsDragging(false)
    handleFiles(e.dataTransfer.files)
  }

  const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault()
    setIsDragging(true)
  }

  const handleDragLeave = () => {
    setIsDragging(false)
  }

  const handleChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      handleFiles(e.target.files)
    },
    [onFilesSelected]
  )

  return (
    <div
      onClick={() => inputRef.current?.click()}
      onDrop={handleDrop}
      onDragOver={handleDragOver}
      onDragLeave={handleDragLeave}
      className={cn(
        "w-full border-2 border-dashed rounded-md p-6 text-center cursor-pointer transition-colors",
        isDragging ? "border-primary bg-muted" : "border-muted-foreground/30"
      )}
    >
      <input
        ref={inputRef}
        type="file"
        multiple
        onChange={handleChange}
        className="hidden"
      />
      <p className="text-sm text-muted-foreground">
        Drag & drop images here or click to upload
      </p>
    </div>
  )
}
