import { useRef, useState } from "react";
import { UploadCloud } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

export function UploadDropzone({
  onFiles,
  heading = "Drop invoices or scanned documents here",
  description = "PDF, JPG or PNG",
  buttonLabel = "Choose files",
  multiple = true,
  size = "compact",
}: {
  onFiles: (names: string[]) => void;
  heading?: string;
  description?: string;
  buttonLabel?: string;
  multiple?: boolean;
  size?: "compact" | "large";
}) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [dragging, setDragging] = useState(false);

  const handle = (list: FileList | null) => {
    const names = list && list.length ? Array.from(list).map((f) => f.name) : [];
    onFiles(names.length ? names : [`scan-${Math.floor(1000 + Math.random() * 8999)}.pdf`]);
  };

  return (
    <div
      onDragOver={(e) => {
        e.preventDefault();
        setDragging(true);
      }}
      onDragLeave={() => setDragging(false)}
      onDrop={(e) => {
        e.preventDefault();
        setDragging(false);
        handle(e.dataTransfer.files);
      }}
      className={cn(
        "flex flex-col items-center justify-center rounded-xl border border-dashed border-border bg-surface text-center transition-colors",
        dragging && "border-primary bg-primary-soft",
        size === "large" ? "px-6 py-14" : "px-6 py-8",
      )}
    >
      <UploadCloud size={size === "large" ? 30 : 24} className="text-primary" aria-hidden="true" />
      <p className={cn("mt-3 font-display text-foreground", size === "large" ? "text-[20px]" : "text-[15px]")}>
        {heading}
      </p>
      <p className="mt-1 text-[12.5px] text-muted-foreground">{description}</p>
      <Button variant="outline" className="mt-4" onClick={() => inputRef.current?.click()}>
        {buttonLabel}
      </Button>
      <input
        ref={inputRef}
        type="file"
        multiple={multiple}
        accept=".pdf,.jpg,.jpeg,.png"
        className="sr-only"
        aria-label="Choose files to upload"
        onChange={(e) => {
          handle(e.target.files);
          e.target.value = "";
        }}
      />
    </div>
  );
}
