"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { apiGet } from "@/lib/api";

type AssignmentAuditItem = {
  id: string;
  label: string;
  href: string;
  note: string;
};

type AssignmentAuditSnapshot = {
  overallTone: "GOOD" | "WATCH" | "URGENT";
  overallLabel: string;
  narrative: string;
  cards: Array<{ key: string; label: string; value: number; helpText: string }>;
  sections: {
    missingEquipmentCoverage: AssignmentAuditItem[];
    missingAssignmentQueueCoverage: AssignmentAuditItem[];
    overdueAssignments: AssignmentAuditItem[];
    readyLoadsWithoutCoverage: AssignmentAuditItem[];
    orphanedAssignments: AssignmentAuditItem[];
  };
};

const toneStyles = {
  GOOD: "border-emerald-200 bg-emerald-50 text-emerald-700",
  WATCH: "border-amber-200 bg-amber-50 text-amber-700",
  URGENT: "border-red-200 bg-red-50 text-red-700",
} as const;

function renderSection(title: string, items: AssignmentAuditItem[], emptyText: string) {
  return (
    <div className="rounded-xl border bg-gray-50 p-4">
      <div className="text-sm font-semibold text-gray-900">{title}</div>
      <div className="mt-3 space-y-2">
        {items.length ? (
          items.map((item) => (
            <div key={item.id} className="rounded-xl border bg-white p-3">
              <Link href={item.href} className="text-sm font-semibold text-gray-900 hover:underline">
                {item.label}
              </Link>
              <div className="mt-1 text-xs text-gray-600">{item.note}</div>
            </div>
          ))
        ) : (
          <div className="rounded-xl border border-dashed bg-white px-3 py-4 text-sm text-gray-500">{emptyText}</div>
        )}
      </div>
    </div>
  );
}

export function AssignmentClosureAudit() {
  const [snapshot, setSnapshot] = useState<AssignmentAuditSnapshot | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    apiGet<AssignmentAuditSnapshot>("/api/assignments/audit")
      .then((data) => {
        setSnapshot(data);
        setError(null);
      })
      .catch((err: any) => setError(err?.message ?? "Failed to load assignment check"));
  }, []);

  if (error) {
    return <section className="rounded-2xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">{error}</section>;
  }

  if (!snapshot) {
    return <section className="rounded-2xl border bg-white p-4 text-sm text-gray-500 shadow-sm">Loading assignment check…</section>;
  }

  return (
    <section className="rounded-2xl border bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-gray-900">Assignment check</div>
          <div className="mt-1 text-xs text-gray-500">
            Checks whether moving loads still have the truck, driver, and next step they need.
          </div>
        </div>
        <div className={`inline-flex rounded-full border px-3 py-1.5 text-xs font-semibold ${toneStyles[snapshot.overallTone]}`}>
          {snapshot.overallLabel}
        </div>
      </div>
      <div className="mt-3 text-sm text-gray-700">{snapshot.narrative}</div>
      <div className="mt-4 grid gap-3 xl:grid-cols-5">
        {snapshot.cards.map((card) => (
          <div key={card.key} className="rounded-xl border bg-gray-50 p-4">
            <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">{card.label}</div>
            <div className="mt-2 text-2xl font-semibold text-gray-900">{card.value}</div>
            <div className="mt-1 text-xs text-gray-600">{card.helpText}</div>
          </div>
        ))}
      </div>
      <div className="mt-4 grid gap-4 xl:grid-cols-2">
        {renderSection("Live loads missing truck or driver", snapshot.sections.missingEquipmentCoverage, "All visible live loads have truck and driver coverage.")}
        {renderSection("Moving loads missing assignment", snapshot.sections.missingAssignmentQueueCoverage, "All visible moving loads have the assignment details they need.")}
        {renderSection("Overdue load-target assignments", snapshot.sections.overdueAssignments, "No open load-target assignments are overdue.")}
        {renderSection("Ready loads still waiting on coverage", snapshot.sections.readyLoadsWithoutCoverage, "No visible ready loads are waiting on truck or driver coverage.")}
      </div>
      {snapshot.sections.orphanedAssignments.length ? (
        <div className="mt-4 rounded-xl border border-amber-200 bg-amber-50 p-4">
          <div className="text-sm font-semibold text-gray-900">Open load-target assignments with no matching active load</div>
          <div className="mt-2 space-y-2">
            {snapshot.sections.orphanedAssignments.map((item) => (
              <div key={item.id} className="rounded-xl border bg-white p-3 text-sm text-gray-700">
                {item.note}
              </div>
            ))}
          </div>
        </div>
      ) : null}
    </section>
  );
}
