"use client";

import { useEffect, useState, type ChangeEvent, type FormEvent } from "react";
import { csrfFetch } from "@/lib/client-csrf";
import { useAdminToast } from "@/components/admin-toast";
import type { SignatoryPublic } from "@/lib/signatories";

export function AdminSignatories() {
  const toast = useAdminToast();
  const [signatories, setSignatories] = useState<SignatoryPublic[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [fullName, setFullName] = useState("Apurvaa Saxena");
  const [professionalTitle, setProfessionalTitle] = useState("Founder and Lead Educator");
  const [active, setActive] = useState(true);
  const [effectiveDate, setEffectiveDate] = useState(() => new Date().toISOString().slice(0, 10));
  const [file, setFile] = useState<File | null>(null);

  async function refresh() {
    setLoading(true);
    try {
      const response = await fetch("/api/admin/signatories", { cache: "no-store" });
      if (!response.ok) {
        toast.error("Could not load signatories.");
        return;
      }
      const data = (await response.json()) as { signatories?: SignatoryPublic[] };
      setSignatories(data.signatories ?? []);
    } catch {
      toast.error("Network error loading signatories.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    let active = true;
    async function loadInitial() {
      try {
        const response = await fetch("/api/admin/signatories", { cache: "no-store" });
        if (!response.ok) return;
        const data = (await response.json()) as { signatories?: SignatoryPublic[] };
        if (active) setSignatories(data.signatories ?? []);
      } finally {
        if (active) setLoading(false);
      }
    }
    void loadInitial();
    return () => {
      active = false;
    };
  }, []);

  function startEdit(row: SignatoryPublic) {
    setEditingId(row.id);
    setFullName(row.fullName);
    setProfessionalTitle(row.professionalTitle);
    setActive(row.active);
    setEffectiveDate(row.effectiveDate.slice(0, 10));
    setFile(null);
  }

  function resetForm() {
    setEditingId(null);
    setFullName("Apurvaa Saxena");
    setProfessionalTitle("Founder and Lead Educator");
    setActive(true);
    setEffectiveDate(new Date().toISOString().slice(0, 10));
    setFile(null);
  }

  async function onSubmit(event: FormEvent) {
    event.preventDefault();
    setSaving(true);
    try {
      const formData = new FormData();
      if (editingId) formData.set("id", editingId);
      formData.set("fullName", fullName);
      formData.set("professionalTitle", professionalTitle);
      formData.set("active", active ? "true" : "false");
      formData.set("effectiveDate", effectiveDate);
      if (file) formData.set("signature", file);

      const response = await csrfFetch("/api/admin/signatories", {
        method: "POST",
        body: formData,
      });
      const data = (await response.json().catch(() => null)) as { error?: string } | null;
      if (!response.ok) {
        toast.error(data?.error || "Could not save signatory.");
        return;
      }
      toast.success(editingId ? "Signatory updated." : "Signatory saved.");
      resetForm();
      await refresh();
    } catch {
      toast.error("Network error saving signatory.");
    } finally {
      setSaving(false);
    }
  }

  function onFileChange(event: ChangeEvent<HTMLInputElement>) {
    const next = event.target.files?.[0] ?? null;
    if (next && (next.type === "image/svg+xml" || next.name.toLowerCase().endsWith(".svg"))) {
      toast.error("SVG is not allowed. Use a transparent PNG or WebP.");
      event.target.value = "";
      setFile(null);
      return;
    }
    setFile(next);
  }

  return (
    <div className="space-y-6">
      <form onSubmit={(event) => void onSubmit(event)} className="rounded-2xl border border-[#d9d0bf] bg-white p-4 shadow-sm sm:p-6">
        <h2 className="text-lg font-semibold text-[#274739]">{editingId ? "Update signatory" : "Certificate signatory"}</h2>
        <p className="mt-1 text-sm text-[#5c5248]">
          Upload Apurvaa Saxena’s signature once as a transparent PNG or WebP. Files are stored privately and embedded
          server-side into certificate PDFs. SVG is not accepted.
        </p>

        <div className="mt-4 grid gap-3 sm:grid-cols-2">
          <label className="block text-sm">
            <span className="font-semibold text-[#3d342c]">Full name</span>
            <input
              className="mt-1 min-h-11 w-full rounded-xl border border-[#d7cbb9] px-3"
              value={fullName}
              onChange={(event) => setFullName(event.target.value)}
              required
            />
          </label>
          <label className="block text-sm">
            <span className="font-semibold text-[#3d342c]">Professional title</span>
            <input
              className="mt-1 min-h-11 w-full rounded-xl border border-[#d7cbb9] px-3"
              value={professionalTitle}
              onChange={(event) => setProfessionalTitle(event.target.value)}
              required
            />
          </label>
          <label className="block text-sm">
            <span className="font-semibold text-[#3d342c]">Effective date</span>
            <input
              type="date"
              className="mt-1 min-h-11 w-full rounded-xl border border-[#d7cbb9] px-3"
              value={effectiveDate}
              onChange={(event) => setEffectiveDate(event.target.value)}
            />
          </label>
          <label className="flex items-end gap-2 pb-2 text-sm font-semibold text-[#3d342c]">
            <input type="checkbox" checked={active} onChange={(event) => setActive(event.target.checked)} />
            Active signatory
          </label>
          <label className="block text-sm sm:col-span-2">
            <span className="font-semibold text-[#3d342c]">Signature image (PNG or WebP)</span>
            <input
              type="file"
              accept="image/png,image/webp"
              className="mt-1 block w-full text-sm"
              onChange={onFileChange}
            />
            <span className="mt-1 block text-[13px] text-[#5c5248]">
              Max 2MB. Metadata is stripped. Replacing the image increments the signature version; previously issued
              certificates keep their snapshot.
            </span>
          </label>
        </div>

        <div className="mt-4 flex flex-wrap gap-2">
          <button
            type="submit"
            disabled={saving}
            className="inline-flex min-h-11 items-center rounded-full bg-[#274739] px-5 text-sm font-semibold text-white disabled:opacity-60"
          >
            {saving ? "Saving…" : editingId ? "Save changes" : "Save signatory"}
          </button>
          {editingId ? (
            <button
              type="button"
              onClick={resetForm}
              className="inline-flex min-h-11 items-center rounded-full border border-[#d7cbb9] px-5 text-sm font-semibold text-[#3d342c]"
            >
              Cancel edit
            </button>
          ) : null}
        </div>
      </form>

      <div className="rounded-2xl border border-[#d9d0bf] bg-white p-4 shadow-sm sm:p-6">
        <h2 className="text-lg font-semibold text-[#274739]">Configured signatories</h2>
        {loading ? <p className="mt-3 text-sm text-[#5c5248]">Loading…</p> : null}
        {!loading && signatories.length === 0 ? (
          <p className="mt-3 text-sm text-[#5c5248]">No signatories yet. Save one above, or run the seed script.</p>
        ) : null}
        <ul className="mt-3 space-y-3">
          {signatories.map((row) => (
            <li key={row.id} className="rounded-xl border border-[#e4d9cb] p-3">
              <div className="flex flex-wrap items-start justify-between gap-3">
                <div>
                  <p className="font-semibold text-[#274739]">{row.fullName}</p>
                  <p className="text-sm text-[#5c5248]">{row.professionalTitle}</p>
                  <p className="mt-1 text-[13px] text-[#8a7a6a]">
                    Version {row.signatureVersion} · {row.active ? "Active" : "Inactive"} · Effective{" "}
                    {new Date(row.effectiveDate).toLocaleDateString("en-IN")}
                    {row.hasSignatureImage ? " · Signature on file" : " · Text line only"}
                  </p>
                </div>
                <div className="flex flex-wrap gap-2">
                  {row.hasSignatureImage ? (
                    // Admin-only authenticated image endpoint — not a public asset path
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={`/api/admin/signatories/${row.id}/image`}
                      alt={`Signature for ${row.fullName}`}
                      className="h-12 w-auto rounded border border-[#e4d9cb] bg-white object-contain p-1"
                    />
                  ) : null}
                  <button
                    type="button"
                    onClick={() => startEdit(row)}
                    className="inline-flex min-h-10 items-center rounded-md border border-[#cfc4b2] px-3 text-sm font-semibold text-[#274739]"
                  >
                    Edit
                  </button>
                </div>
              </div>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}
