import Link from "next/link";
import type { Load } from "@/types";
import { appendReturnTo, buildLoadListQuery } from "@/components/dispatch/dispatch-navigation";

function money(value?: string | null) {
  if (!value) return "-";
  const num = Number(value);
  if (Number.isNaN(num)) return value;
  return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(num);
}

function getAgeDays(load: Load) {
  const payment = [...(load.payments ?? [])].sort((a, b) => new Date(b.invoiceDate || b.createdAt || 0).getTime() - new Date(a.invoiceDate || a.createdAt || 0).getTime())[0];
  const anchor = payment?.invoiceDate || payment?.createdAt || load.deliveryDate;
  if (!anchor) return null;
  const d = new Date(anchor);
  if (Number.isNaN(d.getTime())) return null;
  return Math.max(0, Math.floor((Date.now() - d.getTime()) / (1000 * 60 * 60 * 24)));
}

type Lane = {
  key: string;
  label: string;
  description: string;
  tone: string;
  loads: Load[];
  queueHref: string;
  actionLabel: string;
};

function LaneCard({ lane, returnTo }: { lane: Lane; returnTo?: string }) {
  return (
    <section className="rounded-2xl border bg-white p-4 shadow-sm">
      <div className="flex items-start justify-between gap-3">
        <div>
          <div className="text-sm font-semibold text-slate-900">{lane.label}</div>
          <div className="mt-1 text-xs text-slate-500">{lane.description}</div>
        </div>
        <span className={`rounded-full border px-3 py-1 text-xs font-semibold ${lane.tone}`}>{lane.loads.length}</span>
      </div>

      <div className="mt-4 space-y-3">
        {lane.loads.length ? lane.loads.map((load) => (
          <div key={load.id} className="rounded-xl border p-3">
            <div className="flex flex-wrap items-start justify-between gap-3">
              <div>
                <div className="text-sm font-semibold text-slate-900">{load.referenceNumber || load.id.slice(0, 8)}</div>
                <div className="mt-1 text-xs text-slate-500">{load.broker?.name || "Unassigned broker"} • {load.pickupLocation || "-"} → {load.deliveryLocation || "-"}</div>
              </div>
              <div className="text-right text-xs text-slate-500">
                <div>Outstanding {money(load.financialSummary?.outstandingAmount)}</div>
                <div>{getAgeDays(load) !== null ? `${getAgeDays(load)} days` : "No aging yet"}</div>
              </div>
            </div>
            <div className="mt-3 flex flex-wrap gap-2">
              <Link href={returnTo ? appendReturnTo(`/loads/${load.id}`, returnTo) : `/loads/${load.id}`} className="rounded-lg border px-3 py-1.5 text-xs font-medium">Open load</Link>
              <Link href={returnTo ? appendReturnTo(`/loads/${load.id}/invoice`, returnTo) : `/loads/${load.id}/invoice`} className="rounded-lg border px-3 py-1.5 text-xs font-medium">Open invoice</Link>
            </div>
          </div>
        )) : (
          <div className="rounded-xl border border-dashed p-3 text-sm text-slate-500">No records are currently in this follow-up lane.</div>
        )}
      </div>

      <div className="mt-4">
        <Link href={lane.queueHref} className="text-sm font-medium text-slate-700 underline underline-offset-4">
          {lane.actionLabel}
        </Link>
      </div>
    </section>
  );
}

export function BrokerFollowUpQueue({ loads, returnTo }: { loads: Load[]; returnTo?: string }) {
  const readyToInvoice = loads.filter((load) => load.status === "DELIVERED" && !(load.payments ?? []).length).slice(0, 4);
  const agingCollections = loads
    .filter((load) => (load.status === "INVOICED" || load.status === "PAID_FULL") && Number(load.financialSummary?.outstandingAmount ?? 0) > 0)
    .sort((a, b) => (getAgeDays(b) ?? 0) - (getAgeDays(a) ?? 0))
    .slice(0, 4);
  const missingReference = loads
    .filter((load) => (load.status === "INVOICED" || load.status === "PAID_FULL") && Number(load.financialSummary?.outstandingAmount ?? 0) > 0 && !(load.payments ?? []).some((payment) => payment.paymentReference))
    .sort((a, b) => (getAgeDays(b) ?? 0) - (getAgeDays(a) ?? 0))
    .slice(0, 4);
  const readyForCloseout = loads
    .filter((load) => load.status === "PAID_FULL" || ((load.status === "INVOICED" || load.status === "PAID_FULL") && Number(load.financialSummary?.outstandingAmount ?? 0) <= 0))
    .sort((a, b) => (new Date(b.deliveryDate || 0).getTime()) - (new Date(a.deliveryDate || 0).getTime()))
    .slice(0, 4);

  const lanes: Lane[] = [
    {
      key: "ready-to-invoice",
      label: "Ready for broker follow-up",
      description: "Delivered loads that still need the billing package or first invoice record.",
      tone: "border-blue-200 bg-blue-50 text-blue-800",
      loads: readyToInvoice,
      queueHref: `/loads?${buildLoadListQuery({ uninvoiced: true })}`,
      actionLabel: "Open delivered-awaiting-invoice queue",
    },
    {
      key: "collections",
      label: "Broker collections follow-up",
      description: "Open receivables ordered by the oldest visible invoice anchor first.",
      tone: "border-amber-200 bg-amber-50 text-amber-800",
      loads: agingCollections,
      queueHref: `/loads?${buildLoadListQuery({ status: "INVOICED", unpaid: true })}`,
      actionLabel: "Open active collections queue",
    },
    {
      key: "missing-reference",
      label: "Missing payment reference",
      description: "Open receivables where the broker payment path is still missing a reference or promised-pay note.",
      tone: "border-red-200 bg-red-50 text-red-800",
      loads: missingReference,
      queueHref: `/loads?${buildLoadListQuery({ status: "INVOICED", unpaid: true })}`,
      actionLabel: "Open collections queue for note capture",
    },
    {
      key: "closeout",
      label: "Ready for closeout review",
      description: "Paid or zero-balance records that are leaving the active collections loop and are ready for final operator review.",
      tone: "border-emerald-200 bg-emerald-50 text-emerald-800",
      loads: readyForCloseout,
      queueHref: `/loads?${buildLoadListQuery({ status: "PAID_FULL" })}`,
      actionLabel: "Open paid / closeout queue",
    },
  ];

  return (
    <div className="space-y-4">
      <div>
        <div className="text-sm font-semibold text-slate-900">Broker follow-up queueing</div>
        <div className="text-xs text-slate-500">A focused bridge from dispatch completion into broker billing follow-up and collections execution.</div>
      </div>
      <div className="grid gap-4 xl:grid-cols-2 2xl:grid-cols-4">
        {lanes.map((lane) => (
          <LaneCard key={lane.key} lane={lane} returnTo={returnTo} />
        ))}
      </div>
    </div>
  );
}
