"use client";
import { useCallback, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Upload, X, FileIcon } from "lucide-react";

interface FileUploadProps {
  accept?: string;
  multiple?: boolean;
  maxSizeMB?: number;
  files: File[];
  onChange: (files: File[]) => void;
  label?: string;
}

export function FileUpload({ accept = "image/*", multiple = false, maxSizeMB = 10, files, onChange, label = "Upload files" }: FileUploadProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [error, setError] = useState<string>();

  const handleFiles = useCallback((fileList: FileList) => {
    setError(undefined);
    const newFiles = Array.from(fileList);
    const oversized = newFiles.find((f) => f.size > maxSizeMB * 1024 * 1024);
    if (oversized) { setError(`File "${oversized.name}" exceeds ${maxSizeMB}MB limit`); return; }
    onChange(multiple ? [...files, ...newFiles] : newFiles.slice(0, 1));
  }, [files, maxSizeMB, multiple, onChange]);

  const removeFile = (index: number) => { onChange(files.filter((_, i) => i !== index)); };

  return (
    <div className="space-y-2">
      <div className="border-2 border-dashed rounded-lg p-6 text-center cursor-pointer hover:border-primary/50 transition-colors"
        onClick={() => inputRef.current?.click()}
        onDragOver={(e) => e.preventDefault()}
        onDrop={(e) => { e.preventDefault(); if (e.dataTransfer.files.length) handleFiles(e.dataTransfer.files); }}>
        <Upload className="size-8 mx-auto text-muted-foreground mb-2" />
        <p className="text-sm text-muted-foreground">{label}</p>
        <p className="text-xs text-muted-foreground mt-1">Drag & drop or click to browse (max {maxSizeMB}MB)</p>
      </div>
      <input ref={inputRef} type="file" accept={accept} multiple={multiple} className="hidden"
        onChange={(e) => { if (e.target.files?.length) handleFiles(e.target.files); e.target.value = ""; }} />
      {error && <p className="text-sm text-destructive">{error}</p>}
      {files.length > 0 && (
        <ul className="space-y-1">
          {files.map((file, i) => (
            <li key={i} className="flex items-center gap-2 text-sm rounded border p-2">
              <FileIcon className="size-4 text-muted-foreground shrink-0" />
              <span className="flex-1 truncate">{file.name}</span>
              <span className="text-muted-foreground text-xs">{(file.size / 1024).toFixed(0)}KB</span>
              <Button variant="ghost" size="icon" className="size-6" onClick={(e) => { e.stopPropagation(); removeFile(i); }}>
                <X className="size-3" />
              </Button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
