import { useRef, useState } from "react";
import { Paperclip, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { toast } from "sonner";
import { validateFiles, simulateUpload, MAX_FILES, type UploadedFile } from "@/lib/upload";

export function FileUploader({ files, onChange, label = "Attach files" }: { files: UploadedFile[]; onChange: (f: UploadedFile[]) => void; label?: string }) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState<{ name: string; pct: number }[]>([]);

  async function handle(fs: FileList | null) {
    if (!fs) return;
    const list = Array.from(fs);
    const v = validateFiles([...list, ...(files.map((f) => ({ size: f.size, name: f.name, type: "image/png" } as File)))]);
    if (!v.ok) { toast.error(v.message); return; }
    for (const f of list) {
      setUploading((u) => [...u, { name: f.name, pct: 0 }]);
      // eslint-disable-next-line no-await-in-loop
      const res = await simulateUpload(f, (pct) => setUploading((u) => u.map((x) => x.name === f.name ? { ...x, pct } : x)));
      onChange([...files, res]);
      setUploading((u) => u.filter((x) => x.name !== f.name));
    }
  }

  return (
    <div className="space-y-2">
      <input ref={inputRef} type="file" multiple hidden onChange={(e) => handle(e.target.files)} accept="image/*,application/pdf,text/plain" />
      <Button type="button" variant="outline" size="sm" onClick={() => inputRef.current?.click()} disabled={files.length >= MAX_FILES}>
        <Paperclip className="mr-1.5 h-4 w-4" /> {label}
      </Button>
      <div className="space-y-1.5">
        {files.map((f, i) => (
          <div key={i} className="flex items-center gap-2 rounded-md border border-border bg-surface/60 px-2 py-1.5 text-xs">
            <Paperclip className="h-3.5 w-3.5 text-muted-foreground" />
            <span className="truncate">{f.name}</span>
            <span className="ml-auto text-muted-foreground">{(f.size / 1024).toFixed(0)} kB</span>
            <button type="button" onClick={() => onChange(files.filter((_, j) => j !== i))} className="text-muted-foreground hover:text-foreground"><X className="h-3.5 w-3.5" /></button>
          </div>
        ))}
        {uploading.map((u) => (
          <div key={u.name} className="rounded-md border border-border bg-surface/60 p-2 text-xs">
            <div className="mb-1 flex justify-between"><span className="truncate">{u.name}</span><span className="text-muted-foreground">{u.pct}%</span></div>
            <Progress value={u.pct} className="h-1" />
          </div>
        ))}
      </div>
      <p className="text-[11px] text-muted-foreground">Up to {MAX_FILES} files, 5 MB each. PNG, JPG, WEBP, PDF, TXT.</p>
    </div>
  );
}