"use client";

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

import { VerificationBadge } from "@/components/verification/VerificationBadge";
import { Spinner } from "@/components/common/Spinner";

type CheckSummary = {
  status: string;
  approvedAt: string | null;
  expiresAt: string | null;
  rejectedReason: string | null;
} | null;

type Props = {
  companyId: string;
  companyName: string;
  verificationLevel: number;
  aprPib: string | null;
  aprMaticniBroj: string | null;
  aprFoundedAt: string | null;
  responseTimeMin: number | null;
  checks: Record<string, CheckSummary>;
};

type StepKind = "EMAIL" | "APR" | "ADMIN_PREMIUM";

/* ── Ikone koraka ──────────────────────────────────────────────────────── */
const STEP_ICON: Record<StepKind, ReactNode> = {
  EMAIL: (
    <>
      <rect x="3" y="5" width="18" height="14" rx="2" />
      <path d="m3 7 9 6 9-6" />
    </>
  ),
  APR: (
    <>
      <path d="M3 21h18" />
      <path d="M5 21V8l7-4 7 4v13" />
      <path d="M9 21v-5h6v5" />
      <path d="M9 11h.01M15 11h.01" />
    </>
  ),
  ADMIN_PREMIUM: (
    <>
      <path d="M6 3h12l4 6-10 12L2 9z" />
      <path d="M2 9h20M9 3l3 18M15 3l-3 18" />
    </>
  ),
};

const STEPS: Array<{
  kind: StepKind;
  title: string;
  description: string;
}> = [
  {
    kind: "EMAIL",
    title: "E-mail provera",
    description: "Potvrđen pristup e-mail adresi firme prilikom otvaranja naloga.",
  },
  {
    kind: "APR",
    title: "APR provera",
    description:
      "Potvrda da je firma upisana u Agenciji za privredne registre. Unesite PIB ili matični broj — naš tim potvrđuje upis.",
  },
  {
    kind: "ADMIN_PREMIUM",
    title: "Premium pregled",
    description:
      "Najviši nivo poverenja — pregled našeg tima uz video poziv i dodatne dokumente. Donosi Diamond status profila.",
  },
];

export function VerificationDashboard(props: Props) {
  const router = useRouter();
  const [, startTransition] = useTransition();
  const [pib, setPib] = useState(props.aprPib ?? "");
  const [mb, setMb] = useState(props.aprMaticniBroj ?? "");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [info, setInfo] = useState<string | null>(null);

  async function runApr() {
    setErr(null);
    setInfo(null);
    if (!pib && !mb) {
      setErr("Unesite PIB ili matični broj.");
      return;
    }
    setBusy(true);
    try {
      const res = await fetch("/api/portal/verification/apr", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ pib, maticniBroj: mb }),
      });
      const data = (await res.json()) as {
        ok?: boolean;
        result?: { kind: string; status?: string; naziv?: string; message?: string };
        error?: string;
      };
      if (!res.ok || !data.ok) {
        throw new Error(data.error || "Greška pri proveri.");
      }
      const result = data.result;
      if (result?.kind === "found") {
        setInfo(`APR provera uspešna — firma „${result.naziv}" je aktivna u registru.`);
        startTransition(() => router.refresh());
      } else if (result?.kind === "not-found") {
        setErr("Firma sa tim PIB/MB-om nije pronađena u APR registru. Proverite unos.");
      } else if (result?.kind === "stub") {
        setInfo(
          "Zahtev je primljen. Proveravamo upis u APR registru i potvrđujemo u roku od 24h.",
        );
        startTransition(() => router.refresh());
      } else if (result?.kind === "error") {
        setErr("Trenutno ne možemo da završimo proveru. Pokušajte ponovo malo kasnije.");
      }
    } catch (caught) {
      setErr(caught instanceof Error ? caught.message : "Greška.");
    } finally {
      setBusy(false);
    }
  }

  // Statusi koraka. E-mail je baseline — potvrđuje se pri otvaranju naloga,
  // pa se uvek prikazuje kao verifikovan.
  function stepState(kind: StepKind) {
    const check = props.checks[kind];
    if (kind === "EMAIL") {
      return { status: "APPROVED", check };
    }
    return { status: check?.status ?? "NONE", check };
  }

  const completed = STEPS.filter((s) => stepState(s.kind).status === "APPROVED").length;

  return (
    <section className="space-y-6">
      {/* Trenutni status */}
      <div className="partner-app-panel">
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div>
            <p className="eyebrow">Trenutni nivo</p>
            <div className="mt-3 flex items-center gap-3">
              <VerificationBadge
                level={Math.max(props.verificationLevel, 1)}
                responseTimeMin={props.responseTimeMin}
                aprPib={props.aprPib}
                aprMaticniBroj={props.aprMaticniBroj}
                aprFoundedAt={props.aprFoundedAt ? new Date(props.aprFoundedAt) : null}
              />
              {completed < STEPS.length && (
                <span className="text-xs text-muted-foreground">
                  Sledeći nivo otključavate dole.
                </span>
              )}
            </div>
          </div>

          {/* Progress — koliko koraka je potvrđeno */}
          <div className="flex items-center gap-2" aria-label={`${completed} od ${STEPS.length} koraka`}>
            {STEPS.map((s, i) => (
              <div
                key={s.kind}
                aria-hidden="true"
                className="h-1.5 w-12 rounded-full transition-colors"
                style={{ background: i < completed ? "#c2410c" : "rgba(12,24,40,0.10)" }}
              />
            ))}
          </div>
        </div>
      </div>

      {/* Steps */}
      <div className="grid gap-4 lg:grid-cols-2">
        {STEPS.map((step, index) => {
          const { status, check } = stepState(step.kind);
          const approved = status === "APPROVED";
          const pending = status === "PENDING";
          const rejected = status === "REJECTED";

          return (
            <div
              key={step.kind}
              className="surface relative overflow-hidden rounded-[1.5rem] p-5"
              style={{
                border: approved
                  ? "1px solid rgba(16, 185, 129, 0.30)"
                  : "1px solid var(--border)",
              }}
            >
              <div className="flex items-start gap-3.5">
                {/* Ikona koraka */}
                <span
                  className="flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl"
                  style={{
                    background: approved ? "rgba(16,185,129,0.10)" : "rgba(194,65,12,0.08)",
                    color: approved ? "#059669" : "#c2410c",
                  }}
                >
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.7} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    {STEP_ICON[step.kind]}
                  </svg>
                </span>

                <div className="min-w-0 flex-1">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="eyebrow !text-[0.6rem]">Nivo {index + 1}</p>
                      <h3 className="mt-1 text-lg font-bold leading-snug text-foreground">
                        {step.title}
                      </h3>
                    </div>
                    <StatusPill status={status} />
                  </div>
                  <p className="mt-2 text-sm leading-6 text-muted-foreground">
                    {step.description}
                  </p>
                </div>
              </div>

              {/* Per-step sadržaj */}
              {step.kind === "EMAIL" && (
                <div className="mt-4 flex items-center gap-1.5 pl-[3.6rem] text-xs font-semibold text-emerald-700">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M20 6 9 17l-5-5" />
                  </svg>
                  {check?.approvedAt
                    ? `Potvrđeno ${new Date(check.approvedAt).toLocaleDateString("sr-Latn-RS")}.`
                    : "Potvrđeno prilikom otvaranja portal naloga."}
                </div>
              )}

              {step.kind === "APR" && (
                <div className="mt-4 space-y-3 pl-[3.6rem]">
                  {approved && props.aprPib ? (
                    <div className="rounded-xl border border-emerald-200 bg-emerald-50 p-3 text-sm">
                      <p className="font-bold text-emerald-800">APR provera odobrena</p>
                      <p className="mt-1 text-xs text-emerald-700">
                        {props.aprPib && `PIB: ${props.aprPib}`}
                        {props.aprMaticniBroj && ` · Matični broj: ${props.aprMaticniBroj}`}
                        {props.aprFoundedAt &&
                          ` · od ${new Date(props.aprFoundedAt).getFullYear()}`}
                      </p>
                      {check?.expiresAt && (
                        <p className="mt-1 text-[0.65rem] text-emerald-700/80">
                          Važi do {new Date(check.expiresAt).toLocaleDateString("sr-Latn-RS")}.
                        </p>
                      )}
                    </div>
                  ) : (
                    <>
                      <div className="grid gap-2 sm:grid-cols-2">
                        <input
                          type="text"
                          inputMode="numeric"
                          maxLength={9}
                          placeholder="PIB (9 cifara)"
                          value={pib}
                          onChange={(e) => setPib(e.target.value.replace(/\D/g, ""))}
                          className="rounded-xl border border-[#ede8e3] bg-white px-3 py-2 text-sm outline-none focus:border-[#c2410c]/40 focus:ring-2 focus:ring-[#c2410c]/15"
                        />
                        <input
                          type="text"
                          inputMode="numeric"
                          maxLength={8}
                          placeholder="Matični broj (8 cifara)"
                          value={mb}
                          onChange={(e) => setMb(e.target.value.replace(/\D/g, ""))}
                          className="rounded-xl border border-[#ede8e3] bg-white px-3 py-2 text-sm outline-none focus:border-[#c2410c]/40 focus:ring-2 focus:ring-[#c2410c]/15"
                        />
                      </div>
                      <button
                        type="button"
                        onClick={runApr}
                        disabled={busy}
                        className="primary-button"
                      >
                        {busy ? <Spinner className="h-4 w-4" /> : null}
                        {busy ? "Šaljem zahtev…" : pending ? "Pošalji ponovo" : "Pošalji na proveru"}
                      </button>
                      {pending && !info && (
                        <p className="text-xs font-semibold text-amber-700">
                          Zahtev je primljen — proveravamo upis u APR registru i potvrđujemo u roku od 24h.
                        </p>
                      )}
                      {rejected && check?.rejectedReason && (
                        <p className="text-xs text-red-700">Odbijeno: {check.rejectedReason}</p>
                      )}
                      {info && (
                        <p className="rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-xs font-semibold text-emerald-700">
                          {info}
                        </p>
                      )}
                      {err && (
                        <p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-xs font-semibold text-red-700">
                          {err}
                        </p>
                      )}
                    </>
                  )}
                </div>
              )}

              {step.kind === "ADMIN_PREMIUM" && (
                <div className="mt-4 pl-[3.6rem] text-xs text-muted-foreground">
                  {approved ? (
                    <span className="font-semibold text-emerald-700">
                      Premium pregled odobren — vaš profil ima Diamond status.
                    </span>
                  ) : (
                    <>
                      Aktivira se kroz pregled našeg tima. Zakažite termin preko podrške i pripremite osnovna dokumenta firme.
                    </>
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </section>
  );
}

function StatusPill({ status }: { status: string }) {
  const config: Record<string, { label: string; bg: string; text: string }> = {
    APPROVED: { label: "Verifikovano", bg: "#ecfdf5", text: "#047857" },
    PENDING: { label: "Na čekanju", bg: "#fff7ed", text: "#c2410c" },
    REJECTED: { label: "Odbijeno", bg: "#fef2f2", text: "#b91c1c" },
    EXPIRED: { label: "Isteklo", bg: "#faf9f7", text: "#6b7280" },
    NONE: { label: "Nije pokrenuto", bg: "#faf9f7", text: "#6b7280" },
  };
  const c = config[status] ?? config.NONE;
  return (
    <span
      className="inline-flex shrink-0 items-center rounded-full px-2.5 py-1 text-[0.6rem] font-bold uppercase tracking-[0.10em]"
      style={{ background: c.bg, color: c.text }}
    >
      {c.label}
    </span>
  );
}
