"use client"

import { FileCode2, Upload } from "lucide-react"
import * as React from "react"

import { cn } from "@/lib/utils"

type XmlFileDropzoneProps = {
  onFilesSelected: (fileNames: string[]) => void
  /** Optional hook for size/type validation before names are committed. */
  onFilesChosen?: (files: File[]) => void
  accept?: string
  label?: string
  browseLabel?: string
  multiple?: boolean
}

export function XmlFileDropzone({
  onFilesSelected,
  onFilesChosen,
  accept = ".xml,application/xml,text/xml",
  label = "Drop files here or",
  browseLabel = "Browse XML files",
  multiple = true,
}: XmlFileDropzoneProps) {
  const inputRef = React.useRef<HTMLInputElement>(null)
  const [isDragging, setIsDragging] = React.useState(false)

  const handleFiles = (files: FileList | null) => {
    if (!files?.length) return
    const list = Array.from(files)
    onFilesChosen?.(list)
    onFilesSelected(list.map((f) => f.name))
  }

  return (
    <div
      role="button"
      tabIndex={0}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") inputRef.current?.click()
      }}
      onDragOver={(e) => {
        e.preventDefault()
        setIsDragging(true)
      }}
      onDragLeave={() => setIsDragging(false)}
      onDrop={(e) => {
        e.preventDefault()
        setIsDragging(false)
        handleFiles(e.dataTransfer.files)
      }}
      onClick={() => inputRef.current?.click()}
      className={cn(
        "flex min-h-[220px] cursor-pointer flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed px-6 py-10 transition-colors",
        isDragging
          ? "border-primary bg-primary/5"
          : "border-muted-foreground/30 bg-muted/20 hover:border-primary/50"
      )}
    >
      <input
        ref={inputRef}
        type="file"
        accept={accept}
        multiple={multiple}
        className="sr-only"
        onChange={(e) => handleFiles(e.target.files)}
      />
      <p className="text-sm text-muted-foreground">{label}</p>
      <div className="flex flex-col items-center gap-2">
        <div className="flex size-14 items-center justify-center rounded-lg bg-primary text-primary-foreground">
          <FileCode2 className="size-7" />
        </div>
        <span className="flex items-center gap-1 text-sm font-medium text-primary">
          <Upload className="size-4" />
          {browseLabel}
        </span>
      </div>
    </div>
  )
}
