import { createFileRoute, Link } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { Award, BadgeCheck, Search, ShieldX } from "lucide-react";
import { useState } from "react";

import { PageHeader, PageShell, Reveal } from "@/components/page-shell";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { CREDENTIAL_LEVELS } from "@/lib/assessment";
import { verifyCertificate } from "@/lib/certificates.functions";

export const Route = createFileRoute("/certificates")({
  head: () => ({
    meta: [
      { title: "UZIA Credentials & Certificate Verification | UZIA Academy" },
      {
        name: "description",
        content:
          "The four UZIA credential levels, and a public tool to verify any UZIA Academy certificate by its certificate number.",
      },
      { property: "og:title", content: "UZIA Credentials & Certificate Verification" },
      {
        property: "og:description",
        content: "Verify a UZIA Academy certificate number and see the four credential levels.",
      },
    ],
  }),
  component: CertificatesPage,
});

type Verified = {
  certificate_number: string;
  learner_name: string;
  business_name: string | null;
  course_title: string;
  credential_level: string;
  certificate_type: string;
  learning_hours: number;
  issued_at: string;
};

function CertificatesPage() {
  const verify = useServerFn(verifyCertificate);
  const [number, setNumber] = useState("");
  const [state, setState] = useState<"idle" | "busy" | "found" | "missing">("idle");
  const [record, setRecord] = useState<Verified | null>(null);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!number.trim()) return;
    setState("busy");
    try {
      const result = (await verify({ data: { number } })) as Verified | null;
      setRecord(result);
      setState(result ? "found" : "missing");
    } catch {
      setRecord(null);
      setState("missing");
    }
  }

  return (
    <PageShell>
      <PageHeader
        eyebrow="Credentials"
        title="UZIA certificates, publicly verifiable"
        description="Every completed UZIA programme issues a certificate with a unique number. Buyers, lenders and partners can check it here in seconds."
      />

      <section className="mx-auto w-full max-w-3xl px-4 py-16">
        <Reveal>
          <form
            onSubmit={onSubmit}
            className="rounded-3xl border border-border bg-card p-8 shadow-warm"
          >
            <h2 className="text-2xl">Verify a certificate</h2>
            <p className="mt-2 text-sm text-muted-foreground">
              Enter the certificate number exactly as printed, e.g. UZIA-2026-4F9K2A.
            </p>
            <div className="mt-6 flex flex-col gap-3 sm:flex-row">
              <Input
                value={number}
                onChange={(e) => setNumber(e.target.value)}
                placeholder="UZIA-2026-XXXXXX"
                aria-label="Certificate number"
                className="h-12"
              />
              <Button type="submit" size="lg" className="rounded-full" disabled={state === "busy"}>
                <Search className="mr-2 size-4" />
                {state === "busy" ? "Checking…" : "Verify"}
              </Button>
            </div>
          </form>
        </Reveal>

        {state === "found" && record ? (
          <Reveal>
            <div className="mt-6 overflow-hidden rounded-3xl border border-border bg-card">
              <div className="bg-sunset p-6 text-primary-foreground">
                <BadgeCheck className="size-8 text-gold" />
                <p className="mt-3 font-display text-xl">Valid UZIA certificate</p>
                <p className="mt-1 text-sm opacity-90">{record.certificate_number}</p>
              </div>
              <dl className="grid gap-4 p-6 sm:grid-cols-2">
                {[
                  ["Awarded to", record.learner_name],
                  ["Business", record.business_name ?? "—"],
                  ["Programme", record.course_title],
                  ["Credential level", record.credential_level],
                  ["Certificate type", record.certificate_type],
                  ["Learning hours", `${record.learning_hours} hours`],
                  ["Issued", new Date(record.issued_at).toLocaleDateString()],
                ].map(([k, v]) => (
                  <div key={k}>
                    <dt className="text-xs uppercase tracking-wider text-muted-foreground">{k}</dt>
                    <dd className="mt-1 text-sm font-semibold">{v}</dd>
                  </div>
                ))}
              </dl>
            </div>
          </Reveal>
        ) : null}

        {state === "missing" ? (
          <div className="mt-6 flex items-start gap-3 rounded-3xl border border-destructive/40 bg-destructive/5 p-6">
            <ShieldX className="mt-0.5 size-5 shrink-0 text-destructive" />
            <div>
              <p className="font-semibold">No certificate found</p>
              <p className="mt-1 text-sm text-muted-foreground">
                Check the number for typos. If it still doesn't match, the certificate was not
                issued by UZIA Academy.
              </p>
            </div>
          </div>
        ) : null}

        <div className="mt-16 grid gap-5 sm:grid-cols-2">
          {CREDENTIAL_LEVELS.map((c, i) => (
            <Reveal key={c.level} delay={i * 0.07}>
              <div className="h-full rounded-2xl border border-border bg-surface p-6">
                <Award className="size-6 text-primary" />
                <p className="mt-4 font-display text-lg">Level {c.level}</p>
                <p className="mt-1 text-sm font-semibold">{c.name}</p>
                <p className="mt-2 text-xs text-muted-foreground">{c.note}</p>
              </div>
            </Reveal>
          ))}
        </div>

        <div className="mt-12 text-center">
          <Button asChild variant="outline" className="rounded-full">
            <Link to="/courses">Browse programmes</Link>
          </Button>
        </div>
      </section>
    </PageShell>
  );
}
