"use client";

import { useRouter } from "next/navigation";
import { useRef, useState } from "react";
import { Button, Card } from "@/components/ui";
import { Field, inputClass } from "@/components/ui/form";

export function UploadForm({ siteId }: { siteId: string }) {
  const router = useRouter();
  const formRef = useRef<HTMLFormElement>(null);
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);

  async function submit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const form = new FormData(e.currentTarget);
    const files = form.getAll("file").filter((f): f is File => f instanceof File && f.size > 0);
    if (files.length === 0) return setMessage({ ok: false, text: "Choose at least one file" });
    setBusy(true);
    setMessage(null);
    let done = 0;
    const failures: string[] = [];
    for (const file of files) {
      const body = new FormData();
      body.set("siteId", siteId);
      body.set("file", file);
      for (const key of ["altText", "caption", "attribution", "folder"]) body.set(key, String(form.get(key) ?? ""));
      if (form.get("isPrivate")) body.set("isPrivate", "true");
      try {
        const res = await fetch("/api/media", { method: "POST", body });
        if (res.ok) done++;
        else failures.push(`${file.name}: ${((await res.json().catch(() => ({}))) as { error?: string }).error ?? "upload failed"}`);
      } catch {
        failures.push(`${file.name}: network error`);
      }
    }
    setBusy(false);
    setMessage({ ok: failures.length === 0, text: `${done} uploaded${failures.length ? `. ${failures.join("; ")}` : ""}` });
    if (done > 0) {
      formRef.current?.reset();
      router.refresh();
    }
  }

  return (
    <Card className="mb-4 p-4">
      <form ref={formRef} onSubmit={submit} className="grid gap-4 sm:grid-cols-2" noValidate>
        <Field id="up-file" label="Files" help="PNG, JPEG, GIF, WebP or PDF, up to 20 MB each." className="sm:col-span-2">
          <input id="up-file" name="file" type="file" multiple accept="image/png,image/jpeg,image/gif,image/webp,application/pdf" className={inputClass} />
        </Field>
        <Field id="up-alt" label="Alt text" help="Describe the image for people who can’t see it. Applied to every file in this upload."><input id="up-alt" name="altText" maxLength={250} className={inputClass} /></Field>
        <Field id="up-folder" label="Folder"><input id="up-folder" name="folder" maxLength={60} className={inputClass} /></Field>
        <Field id="up-caption" label="Caption"><input id="up-caption" name="caption" maxLength={500} className={inputClass} /></Field>
        <Field id="up-attr" label="Credit / attribution"><input id="up-attr" name="attribution" maxLength={255} className={inputClass} /></Field>
        <label className="flex items-center gap-2 text-sm sm:col-span-2"><input type="checkbox" name="isPrivate" /> Private (only signed-in team members or signed links can open it; can’t be used on pages)</label>
        <div className="flex items-center gap-3 sm:col-span-2">
          <Button type="submit" disabled={busy}>{busy ? "Uploading…" : "Upload"}</Button>
          {message ? <p role={message.ok ? "status" : "alert"} className={message.ok ? "text-sm text-success" : "text-sm text-danger"}>{message.text}</p> : null}
        </div>
      </form>
    </Card>
  );
}
