import Link from "next/link";
import type { Load, LoadPayment } from "@/types";
import { appendReturnTo } 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 formatDate(value?: string | null) {
  if (!value) return "-";
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString();
}

function daysSince(value?: string | null) {
  if (!value) return null;
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return null;
  const today = new Date();
  const diffMs = today.getTime() - d.getTime();
  return Math.max(0, Math.floor(diffMs / (1000 * 60 * 60 * 24)));
}

function latestPayment(load: Load): LoadPayment | null {
  return [...(load.payments ?? [])].sort((a, b) => {
    const aDate = new Date(a.invoiceDate || a.createdAt || 0).getTime();
    const bDate = new Date(b.invoiceDate || b.createdAt || 0).getTime();
    return bDate - aDate;
  })[0] ?? null;
}

function getInvoiceAnchorDate(load: Load, payment: LoadPayment | null) {
  return payment?.invoiceDate || payment?.createdAt || load.deliveryDate || null;
}

function getAgingBucket(days: number | null) {
  if (days === null) return { label: "Not aging yet", tone: "border-slate-200 bg-slate-50 text-slate-700" };
  if (days <= 15) return { label: "0-15 days", tone: "border-emerald-200 bg-emerald-50 text-emerald-700" };
  if (days <= 30) return { label: "16-30 days", tone: "border-amber-200 bg-amber-50 text-amber-700" };
  if (days <= 45) return { label: "31-45 days", tone: "border-orange-200 bg-orange-50 text-orange-700" };
  return { label: "46+ days", tone: "border-red-200 bg-red-50 text-red-700" };
}

function getCollectionAction(load: Load, payment: LoadPayment | null, ageDays: number | null) {
  const outstanding = Number(load.financialSummary?.outstandingAmount ?? 0);
  const invoiceExists = Boolean(payment?.invoiceNumber || (load.payments ?? []).length);

  if (!invoiceExists && load.status === "DELIVERED") return "Create invoice record and send billing package";
  if (load.status !== "INVOICED" && load.status !== "PAID_FULL" && load.status !== "DELIVERED") return "Complete delivery and invoice steps first";
  if (outstanding <= 0 && invoiceExists) return "Collections loop is closed";
  if (!payment?.paymentReference && ageDays !== null && ageDays >= 30) return "Call broker AP and capture payment reference";
  if (!payment?.paymentReference && invoiceExists) return "Send follow-up and request payment reference";
  if (ageDays !== null && ageDays >= 45) return "Escalate collections and verify broker AP path";
  if (ageDays !== null && ageDays >= 16) return "Run structured collections follow-up";
  return "Monitor receivable and confirm expected payment date";
}

export function PaymentCollectionVisibilityPanel({ load, returnTo }: { load: Load; returnTo?: string }) {
  const payment = latestPayment(load);
  const outstanding = Number(load.financialSummary?.outstandingAmount ?? 0);
  const ageDays = daysSince(getInvoiceAnchorDate(load, payment));
  const bucket = getAgingBucket(ageDays);
  const nextAction = getCollectionAction(load, payment, ageDays);
  const latestFollowUpNote = payment?.notesText || load.statusHistory?.find((item) => item.note)?.note || null;
  const collectionOpen = outstanding > 0 && (load.status === "INVOICED" || load.status === "PAID_FULL" || Boolean(payment));

  const summaryItems = [
    { label: "Outstanding", value: money(load.financialSummary?.outstandingAmount) },
    { label: "Invoice", value: payment?.invoiceNumber || "Not yet created" },
    { label: "Broker AP path", value: load.broker?.phone || "No direct broker phone on record" },
    { label: "Payment reference", value: payment?.paymentReference || "Not yet captured" },
  ];

  return (
    <section className="rounded-2xl border bg-white p-5 shadow-sm">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <div className="text-sm font-semibold text-slate-900">Payment follow-up</div>
          <div className="text-xs text-slate-500">Keep broker collections, payment references, and invoice ownership visible from the same load record.</div>
        </div>
        <Link href={returnTo ? appendReturnTo(`/loads/${load.id}/invoice`, returnTo) : `/loads/${load.id}/invoice`} className="rounded-xl border bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
          Open payment follow-up
        </Link>
      </div>

      <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
        {summaryItems.map((item) => (
          <div key={item.label} className="rounded-2xl border bg-slate-50 p-4">
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">{item.label}</div>
            <div className="mt-2 text-sm font-semibold text-slate-900">{item.value}</div>
          </div>
        ))}
      </div>

      <div className="mt-4 grid gap-4 lg:grid-cols-[1.05fr_0.95fr]">
        <div className="rounded-2xl border p-4">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <div>
              <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Next collection action</div>
              <div className="mt-2 text-sm font-semibold text-slate-900">{nextAction}</div>
            </div>
            <div className={`rounded-full border px-3 py-1 text-xs font-semibold ${bucket.tone}`}>{bucket.label}</div>
          </div>
          <div className="mt-3 text-sm text-slate-600">
            {collectionOpen
              ? `Payment follow-up is open${ageDays !== null ? ` • ${ageDays} day${ageDays === 1 ? "" : "s"} since invoice date` : ""}`
              : "Collections are not yet active on this load."}
          </div>
          <div className="mt-4 grid gap-2 text-sm text-slate-700">
            <div><span className="font-medium">Invoice date:</span> {formatDate(getInvoiceAnchorDate(load, payment))}</div>
            <div><span className="font-medium">Payment status:</span> {load.financialSummary?.paymentStatusSummary || payment?.paymentStatus || "-"}</div>
            <div><span className="font-medium">Amount paid:</span> {money(load.financialSummary?.amountPaidTotal || payment?.amountPaid)}</div>
            <div><span className="font-medium">Outstanding:</span> {money(load.financialSummary?.outstandingAmount || payment?.amountDue)}</div>
          </div>
        </div>

        <div className="rounded-2xl border p-4">
          <div className="text-sm font-semibold text-slate-900">Collections follow-up notes</div>
          <div className="mt-3 space-y-2 text-sm text-slate-700">
            <div><span className="font-medium">Broker:</span> {load.broker?.name || "Unassigned broker"}</div>
            <div><span className="font-medium">Broker phone:</span> {load.broker?.phone || "No phone captured"}</div>
            <div><span className="font-medium">Latest note:</span> {latestFollowUpNote || "No visible collections or billing note captured yet."}</div>
            <div><span className="font-medium">Paid at:</span> {formatDate(payment?.paidAt)}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

export function InvoiceAgingActionabilityPanel({ load, returnTo }: { load: Load; returnTo?: string }) {
  const payment = latestPayment(load);
  const ageDays = daysSince(getInvoiceAnchorDate(load, payment));
  const outstanding = Number(load.financialSummary?.outstandingAmount ?? 0);
  const bucket = getAgingBucket(ageDays);
  const actionableStates = [
    {
      label: "Age",
      value: ageDays === null ? "Not aging yet" : `${ageDays} days`,
      detail: ageDays === null ? "Invoice anchor date not available yet." : `Current aging bucket: ${bucket.label}`,
    },
    {
      label: "Exposure",
      value: outstanding > 0 ? money(load.financialSummary?.outstandingAmount) : "No open exposure",
      detail: outstanding > 0 ? "Receivable is still open." : "Invoice balance appears closed.",
    },
    {
      label: "Action path",
      value: getCollectionAction(load, payment, ageDays),
      detail: payment?.paymentReference ? `Reference ${payment.paymentReference}` : "No payment reference captured yet.",
    },
  ];

  const prompts = [
    ageDays !== null && ageDays >= 45 ? "Escalate collections and verify AP ownership today." : null,
    ageDays !== null && ageDays >= 30 ? "Call broker billing contact and capture a payment commitment." : null,
    outstanding > 0 && !payment?.paymentReference ? "Add payment reference or promised-pay-date notes to keep follow-up anchored." : null,
    outstanding <= 0 ? "Mark collections complete and keep the record ready for closed-loop review." : null,
  ].filter(Boolean) as string[];

  return (
    <section className="rounded-2xl border bg-white p-5 shadow-sm">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <div className="text-sm font-semibold text-slate-900">Invoice aging actionability</div>
          <div className="text-xs text-slate-500">Turn invoice age into the next clear payment step.</div>
        </div>
        <Link href={returnTo ? appendReturnTo(`/loads/${load.id}/invoice`, returnTo) : `/loads/${load.id}/invoice`} className="rounded-xl border bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
          Open invoice detail
        </Link>
      </div>

      <div className="mt-4 grid gap-3 md:grid-cols-3">
        {actionableStates.map((item) => (
          <div key={item.label} className="rounded-2xl border p-4">
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">{item.label}</div>
            <div className="mt-2 text-sm font-semibold text-slate-900">{item.value}</div>
            <div className="mt-2 text-xs text-slate-500">{item.detail}</div>
          </div>
        ))}
      </div>

      <div className="mt-4 rounded-2xl border p-4">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div className="text-sm font-semibold text-slate-900">Aging bucket guidance</div>
          <div className={`rounded-full border px-3 py-1 text-xs font-semibold ${bucket.tone}`}>{bucket.label}</div>
        </div>
        <div className="mt-3 space-y-2 text-sm text-slate-700">
          {prompts.length ? prompts.map((prompt) => (
            <div key={prompt} className="rounded-xl border border-slate-200 bg-slate-50 px-3 py-2">{prompt}</div>
          )) : (
            <div className="rounded-xl border border-slate-200 bg-slate-50 px-3 py-2">No invoice-aging prompt is active on this load yet.</div>
          )}
        </div>
      </div>
    </section>
  );
}
