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

function formatDateTime(value?: string | null) {
  if (!value) return "-";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleString();
}

function hasInvoiceRecord(load: Load) {
  return Boolean(load.payments?.some((payment) => payment.invoiceNumber));
}

function latestStatusNote(load: Load) {
  const history = [...(load.statusHistory ?? [])].sort(
    (a, b) => new Date(b.changedAt).getTime() - new Date(a.changedAt).getTime(),
  );
  return history.find((item) => item.note?.trim()) ?? history[0] ?? null;
}

function readinessTone(ready: boolean, watch = false) {
  if (ready) return "border-emerald-200 bg-emerald-50 text-emerald-800";
  if (watch) return "border-amber-200 bg-amber-50 text-amber-800";
  return "border-red-200 bg-red-50 text-red-800";
}

export function DocumentHandoffReadinessPanel({
  load,
  returnTo,
}: {
  load: Load;
  returnTo?: string;
}) {
  const invoiceReady = load.status === "DELIVERED" || load.status === "INVOICED" || load.status === "PAID_FULL";
  const items = [
    {
      key: "ratecon",
      label: "Rate confirmation visibility",
      ready: Boolean(load.rateConfirmationNumber),
      watch: true,
      body: load.rateConfirmationNumber
        ? `Rate confirmation ${load.rateConfirmationNumber} is already on the load record for paperwork follow-up.`
        : "Rate confirmation number is missing. Billing can continue, but paperwork follow-up will be weaker.",
    },
    {
      key: "broker",
      label: "Broker billing contact path",
      ready: Boolean(load.broker?.name && load.broker?.phone),
      watch: Boolean(load.broker?.name),
      body: load.broker?.name
        ? `${load.broker.name}${load.broker.phone ? ` · ${load.broker.phone}` : ""}`
        : "Broker contact visibility is incomplete for POD and invoice follow-up.",
    },
    {
      key: "delivery",
      label: "Delivery stage",
      ready: invoiceReady,
      watch: load.status === "IN_TRANSIT",
      body: invoiceReady
        ? "The load is at or beyond delivery stage, so POD and invoice controls should stay active."
        : load.status === "IN_TRANSIT"
          ? "Keep receiver timing and final ETA visible so paperwork can be handled promptly after delivery."
          : "The load has not reached delivery stage yet.",
    },
    {
      key: "invoice-record",
      label: "Invoice record",
      ready: hasInvoiceRecord(load) || load.status === "INVOICED" || load.status === "PAID_FULL",
      watch: load.status === "DELIVERED",
      body: hasInvoiceRecord(load)
        ? "An invoice record already exists on this load."
        : load.status === "DELIVERED"
          ? "Delivery is complete but the invoice record still needs to be created while details are fresh."
          : "Invoice creation is not the next critical step yet.",
    },
  ];

  const invoiceHref = returnTo ? appendReturnTo(`/loads/${load.id}/invoice`, returnTo) : `/loads/${load.id}/invoice`;

  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">Paperwork check</div>
          <div className="text-xs text-slate-500">A quick check for billing and POD follow-up.</div>
        </div>
        <Link href={invoiceHref} className="rounded-xl border bg-white px-3 py-2 text-xs font-semibold text-slate-800">
          Open invoice
        </Link>
      </div>

      <div className="mt-4 grid gap-3 md:grid-cols-2">
        {items.map((item) => (
          <div key={item.key} className={`rounded-xl border px-4 py-3 ${readinessTone(item.ready, item.watch)}`}>
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em]">{item.label}</div>
            <div className="mt-2 text-sm leading-6">{item.body}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

export function PodInvoiceTransitionVisibilityPanel({
  load,
  returnTo,
}: {
  load: Load;
  returnTo?: string;
}) {
  const note = latestStatusNote(load);
  const invoiceRecord = hasInvoiceRecord(load);
  const outstanding = Number(load.financialSummary?.outstandingAmount ?? 0);
  const steps = [
    {
      key: "dispatch",
      label: "Dispatch execution",
      state: ["ASSIGNED", "IN_TRANSIT", "DELIVERED", "INVOICED", "PAID_FULL"].includes(load.status) ? "complete" : load.status === "AVAILABLE" ? "current" : "upcoming",
      detail: load.driver?.id && load.truck?.id ? "Truck and driver are attached to the load." : "Truck and driver assignment still need attention.",
    },
    {
      key: "delivered",
      label: "Delivered",
      state: ["DELIVERED", "INVOICED", "PAID_FULL"].includes(load.status) ? "complete" : load.status === "IN_TRANSIT" ? "current" : "upcoming",
      detail: load.status === "IN_TRANSIT" ? "Keep final ETA and receiver timing visible." : "Delivery completion should be captured before billing closes.",
    },
    {
      key: "pod-handoff",
      label: "POD / paperwork",
      state: invoiceRecord || ["INVOICED", "PAID_FULL"].includes(load.status) ? "complete" : load.status === "DELIVERED" ? "current" : "upcoming",
      detail: note ? `Latest visible note: ${note.note?.trim() || note.toStatus.replaceAll("_", " ")} · ${formatDateTime(note.changedAt)}` : "No recent delivery note is visible on status history yet.",
    },
    {
      key: "invoice",
      label: "Invoice transition",
      state: ["INVOICED", "PAID_FULL"].includes(load.status) ? "complete" : load.status === "DELIVERED" ? "current" : "upcoming",
      detail: invoiceRecord ? "Invoice record exists." : "Create the invoice record while delivery details are fresh.",
    },
    {
      key: "collections",
      label: "Collections",
      state: load.status === "PAID_FULL" || outstanding <= 0 ? "complete" : load.status === "INVOICED" ? "current" : "upcoming",
      detail: outstanding > 0 ? `Outstanding balance remains visible at ${new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(outstanding)}.` : "No open balance remains on this load.",
    },
  ] as const;

  const stateClasses = {
    complete: "border-emerald-200 bg-emerald-50",
    current: "border-slate-900 bg-slate-50",
    upcoming: "border-slate-200 bg-white",
  } as const;

  const invoiceHref = returnTo ? appendReturnTo(`/loads/${load.id}/invoice`, returnTo) : `/loads/${load.id}/invoice`;

  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">POD / invoice transition visibility</div>
          <div className="text-xs text-slate-500">A simple path from dispatch to paperwork, invoice creation, and payment follow-up.</div>
        </div>
        <div className="flex flex-wrap gap-2">
          <Link href={invoiceHref} className="rounded-xl border bg-white px-3 py-2 text-xs font-semibold text-slate-800">
            Invoice controls
          </Link>
          <Link href={returnTo ? appendReturnTo(`/loads/${load.id}`, returnTo) : `/loads/${load.id}`} className="rounded-xl border bg-white px-3 py-2 text-xs font-semibold text-slate-800">
            Load record
          </Link>
        </div>
      </div>

      <div className="mt-4 space-y-3">
        {steps.map((step) => (
          <div key={step.key} className={`rounded-xl border px-4 py-3 ${stateClasses[step.state]}`}>
            <div className="flex flex-wrap items-center justify-between gap-2">
              <div className="text-sm font-semibold text-slate-900">{step.label}</div>
              <div className="rounded-full border bg-white px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-700">
                {step.state}
              </div>
            </div>
            <div className="mt-1 text-sm text-slate-600">{step.detail}</div>
          </div>
        ))}
      </div>
    </section>
  );
}
