"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
  disabled?: boolean
}

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

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

  return (
    <div
      role="button"
      tabIndex={disabled ? -1 : 0}
      aria-disabled={disabled}
      onKeyDown={(e) => {
        if (disabled) return
        if (e.key === "Enter" || e.key === " ") inputRef.current?.click()
      }}
      onDragOver={(e) => {
        e.preventDefault()
        if (!disabled) setIsDragging(true)
      }}
      onDragLeave={() => setIsDragging(false)}
      onDrop={(e) => {
        e.preventDefault()
        setIsDragging(false)
        handleFiles(e.dataTransfer.files)
      }}
      onClick={() => {
        if (!disabled) inputRef.current?.click()
      }}
      className={cn(
        "flex min-h-[220px] flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed px-6 py-10 transition-colors",
        disabled ? "cursor-default opacity-70" : "cursor-pointer",
        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}
        disabled={disabled}
        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>
  )
}
