"use client";

import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";

export function ProjectMediaUploader({ projectId }: { projectId: string }) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);
  const [ok, setOk] = useState<string | null>(null);

  function onChange(event: React.ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];
    if (!file) return;

    setError(null);
    setOk(null);

    startTransition(async () => {
      const body = new FormData();
      body.set("projectId", projectId);
      body.set("file", file);
      if (file.name) body.set("altText", file.name.replace(/\.[^.]+$/, ""));

      const res = await fetch("/api/dashboard/media", {
        method: "POST",
        body,
      });

      const data = (await res.json()) as { error?: string; id?: string };
      if (!res.ok) {
        setError(data.error ?? "Upload failed");
        return;
      }

      setOk("Uploaded");
      router.refresh();
      event.target.value = "";
    });
  }

  return (
    <div>
      <label className="inline-flex cursor-pointer items-center gap-3 border border-[var(--archi-line)] bg-white/70 px-4 py-3 text-sm">
        <span>{pending ? "Uploading…" : "Upload image or PDF"}</span>
        <input
          type="file"
          accept="image/jpeg,image/png,image/webp,image/avif,image/gif,application/pdf"
          className="sr-only"
          disabled={pending}
          onChange={onChange}
        />
      </label>
      {error ? (
        <p className="mt-2 text-sm text-red-800" role="alert">
          {error}
        </p>
      ) : null}
      {ok ? (
        <p className="mt-2 text-sm text-[var(--archi-accent)]" role="status">
          {ok}
        </p>
      ) : null}
    </div>
  );
}
