"use client";

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

export type LoadContinuityAuditItem = {
  id: string;
  label: string;
  href: string;
  note: string;
};

export type LoadContinuityAuditSnapshot = {
  overallTone: "GOOD" | "WATCH" | "URGENT";
  overallLabel: string;
  cards: Array<{ key: string; label: string; value: number; helpText: string }>;
  prompts: string[];
  sections: {
    missingCoverage: LoadContinuityAuditItem[];
    dateGaps: LoadContinuityAuditItem[];
    movingMissingDocs: LoadContinuityAuditItem[];
    deliveredUninvoiced: LoadContinuityAuditItem[];
    invoicedUnpaid: LoadContinuityAuditItem[];
  };
};

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: LoadContinuityAuditItem[], 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 LoadManagementContinuityAudit({ compact = false }: { compact?: boolean }) {
  const [snapshot, setSnapshot] = useState<LoadContinuityAuditSnapshot | null>(null);
  const [error, setError] = useState<string | null>(null);

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

  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 load check…</section>;

  return (
    <section className={`rounded-2xl border bg-white shadow-sm ${compact ? "p-4" : "p-6"}`}>
      <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">Load management check</div>
          <div className="mt-1 text-xs text-gray-500">Checks whether coverage, dates, paperwork, invoice work, and collections follow-up still line up.</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-4 grid gap-3 ${compact ? "md:grid-cols-2 xl:grid-cols-3" : "xl:grid-cols-6"}`}>
        {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 ${compact ? "" : "xl:grid-cols-[0.95fr_1.05fr]"}`}>
        <div className="rounded-xl border bg-gray-50 p-4">
          <div className="text-sm font-semibold text-gray-900">Continuity prompts</div>
          <div className="mt-3 space-y-2">
            {snapshot.prompts.length ? snapshot.prompts.map((prompt) => (
              <div key={prompt} className="rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">{prompt}</div>
            )) : <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800">No visible load gaps remain right now.</div>}
          </div>
        </div>
        <div className="grid gap-4 xl:grid-cols-2">
          {renderSection("Missing truck or driver coverage", snapshot.sections.missingCoverage, "All active loads have truck and driver coverage.")}
          {renderSection("Missing pickup or delivery dates", snapshot.sections.dateGaps, "All active loads have pickup and delivery dates set.")}
          {renderSection("Movement paperwork gaps", snapshot.sections.movingMissingDocs, "No moving or delivered loads are missing BOL or POD anchors.")}
          {renderSection("Delivered still not invoiced", snapshot.sections.deliveredUninvoiced, "No delivered loads are waiting on invoice follow-up.")}
          {renderSection("Invoiced still open in collections", snapshot.sections.invoicedUnpaid, "No invoiced loads are waiting on collections follow-through.")}
        </div>
      </div>
    </section>
  );
}
