"use client";

import Link from "next/link";
import { CallCopilotLink } from "@/components/cori/call-copilot-link";
import { FormEvent, useEffect, useMemo, useState } from "react";
import { useParams, useSearchParams } from "next/navigation";
import { apiGet, apiPost } from "@/lib/api";
import type { DocumentLifecycleSnapshot, Driver, Load, LoadAccessorial, LoadPayment, Truck } from "@/types";
import { PageHeader } from "@/components/ui/page-header";
import { AssignmentPanel } from "@/components/crm/assignment-panel";
import { getInvoiceDate, getInvoiceNumber } from "@/src/modules/loads/invoice";
import { LoadBillingReadinessPanel } from "@/components/loads-billing-readiness-panel";
import { LoadsDocumentCompliancePanel } from "@/components/loads-document-compliance-panel";
import { LoadsDocumentIntakePanel } from "@/components/loads-document-intake-panel";
import { AssignmentComplianceReadinessPanel } from "@/components/assignment-compliance-readiness-panel";
import { LoadDocumentAccessPanel } from "@/components/load-document-access-panel";
import { DocumentLifecycleUnification } from "@/components/documents/document-lifecycle-unification";
import { LoadManagementContinuityAudit } from "@/components/loads/load-management-continuity-audit";
import { WorkspaceHandoffPanel } from "@/components/continuity/workspace-handoff-panel";
import { UniversalQuickActions } from "@/components/continuity/universal-quick-actions";
import { appendReturnTo, resolveReturnTo } from "@/src/modules/loads/load-navigation";

function Card({ title, children, action }: { title: string; children: React.ReactNode; action?: React.ReactNode }) {
  return (
    <section className="rounded-2xl border bg-white p-6 shadow-sm">
      <div className="mb-4 flex items-center justify-between gap-4">
        <h3 className="text-base font-semibold">{title}</h3>
        {action}
      </div>
      {children}
    </section>
  );
}

function Row({ label, value }: { label: string; value?: React.ReactNode }) {
  return (
    <div className="grid grid-cols-1 gap-1 border-b py-3 last:border-b-0 md:grid-cols-[180px_1fr]">
      <div className="text-sm font-medium text-gray-600">{label}</div>
      <div className="text-sm text-gray-900">{value || "-"}</div>
    </div>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="block space-y-1">
      <span className="text-sm font-medium text-gray-700">{label}</span>
      {children}
    </label>
  );
}

function Input(props: React.InputHTMLAttributes<HTMLInputElement>) {
  return <input {...props} className={`w-full rounded-xl border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-black/10 ${props.className ?? ""}`} />;
}

function Select(props: React.SelectHTMLAttributes<HTMLSelectElement>) {
  return <select {...props} className={`w-full rounded-xl border bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-black/10 ${props.className ?? ""}`} />;
}

function TextArea(props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) {
  return <textarea {...props} className={`w-full rounded-xl border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-black/10 ${props.className ?? ""}`} />;
}

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 dateTime(value?: string | null) {
  if (!value) return "-";
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? value : d.toLocaleString();
}


function sameDay(value?: string | null) {
  if (!value) return false;
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return false;
  const today = new Date();
  return d.toISOString().slice(0, 10) === today.toISOString().slice(0, 10);
}

function isPastDay(value?: string | null) {
  if (!value) return false;
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return false;
  const today = new Date();
  return d.toISOString().slice(0, 10) < today.toISOString().slice(0, 10);
}

function getNextOperationalAction(load: Load) {
  if ((load.status === "AVAILABLE" || load.status === "DRAFT") && (!load.driver?.id || !load.truck?.id)) return "Assign truck and driver";
  if ((load.status === "AVAILABLE" || load.status === "ASSIGNED") && sameDay(load.pickupDate)) return "Confirm pickup and dispatch out";
  if (load.status === "IN_TRANSIT" && isPastDay(load.deliveryDate)) return "Resolve late-delivery exception";
  if (load.status === "IN_TRANSIT" && sameDay(load.deliveryDate)) return "Confirm delivery details";
  if (load.status === "IN_TRANSIT") return "Capture check call and ETA";
  if (load.status === "DELIVERED") return "Create invoice";
  if (load.status === "INVOICED" && Number(load.financialSummary?.outstandingAmount ?? 0) > 0) return "Follow up on payment";
  if (load.status === "PAID_FULL") return "Archive / closed loop";
  return "Monitor load progress";
}

function getQuickStatusActions(load: Load) {
  const map: Record<string, { label: string; status: string }[]> = {
    DRAFT: [{ label: "Make available", status: "AVAILABLE" }],
    AVAILABLE: [{ label: "Assign", status: "ASSIGNED" }],
    ASSIGNED: [{ label: "Picked up", status: "IN_TRANSIT" }],
    IN_TRANSIT: [{ label: "Delivered", status: "DELIVERED" }],
    DELIVERED: [{ label: "Invoiced", status: "INVOICED" }],
    INVOICED: [{ label: "Paid in full", status: "PAID_FULL" }],
  };
  return map[load.status] ?? [];
}

function StatusPill({ status }: { status?: string | null }) {
  return (
    <span className="inline-flex rounded-full border bg-white px-3 py-1 text-xs font-semibold tracking-wide text-gray-700">
      {status || "-"}
    </span>
  );
}

function MetricCard({ label, value }: { label: string; value?: React.ReactNode }) {
  return (
    <div className="rounded-2xl border bg-white p-4 shadow-sm">
      <div className="text-xs font-semibold uppercase tracking-[0.16em] text-gray-500">{label}</div>
      <div className="mt-2 text-base font-semibold text-gray-900">{value || "-"}</div>
    </div>
  );
}

export default function LoadDetailPage() {
  const params = useParams<{ id: string }>();
  const searchParams = useSearchParams();
  const requestedReturnTo = searchParams.get("returnTo");
  const resolvedReturnTo = resolveReturnTo(requestedReturnTo, "/loads");
  const [load, setLoad] = useState<Load | null>(null);
  const [assignedDriver, setAssignedDriver] = useState<Driver | null>(null);
  const [assignedTruck, setAssignedTruck] = useState<Truck | null>(null);
  const [documentLifecycle, setDocumentLifecycle] = useState<DocumentLifecycleSnapshot | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [working, setWorking] = useState(false);
  const [nextStatus, setNextStatus] = useState("DRAFT");
  const [addingAccessorial, setAddingAccessorial] = useState(false);
  const [addingPayment, setAddingPayment] = useState(false);
  const [accessorialForm, setAccessorialForm] = useState({ category: "DETENTION", amount: "", description: "" });
  const [paymentForm, setPaymentForm] = useState({ paymentStatus: "UNPAID", invoiceNumber: "", invoiceDate: "", amountDue: "", amountPaid: "", paidAt: "", paymentReference: "", notesText: "" });

  async function loadRecord() {
    if (!params?.id) return;
    try {
      setError(null);
      const data = await apiGet<{ load: Load }>(`/api/loads/${params.id}`);
      setLoad(data.load);
      setNextStatus(data.load.status || "DRAFT");
      setPaymentForm((current) => ({
        ...current,
        invoiceNumber: current.invoiceNumber || getInvoiceNumber(data.load),
        invoiceDate: current.invoiceDate || getInvoiceDate(data.load),
        amountDue: current.amountDue || data.load.financialSummary?.grossRevenue || data.load.invoiceAmount || "",
      }));

      const [driverData, truckData, lifecycleData] = await Promise.all([
        data.load.driver?.id ? apiGet<{ driver: Driver }>(`/api/drivers/${data.load.driver.id}`).catch(() => null) : Promise.resolve(null),
        data.load.truck?.id ? apiGet<{ truck: Truck }>(`/api/trucks/${data.load.truck.id}`).catch(() => null) : Promise.resolve(null),
        apiGet<DocumentLifecycleSnapshot>("/api/documents/lifecycle").catch(() => null),
      ]);
      setAssignedDriver(driverData?.driver ?? null);
      setAssignedTruck(truckData?.truck ?? null);
      setDocumentLifecycle(lifecycleData ?? null);
    } catch (err: any) {
      setError(err?.message ?? "Failed to load record");
    }
  }

  useEffect(() => {
    loadRecord();
  }, [params?.id]);

  const accessorials = load?.accessorials ?? [];
  const payments = load?.payments ?? [];

  const openBalance = useMemo(() => load?.financialSummary?.outstandingAmount ?? load?.financialSummary?.grossRevenue ?? load?.invoiceAmount ?? null, [load]);
  const continuitySummary = useMemo(() => ([
    requestedReturnTo ? "Opened from a scoped queue" : "Opened directly",
    `Return target: ${requestedReturnTo ? "Previous list or workflow" : "Loads"}`,
    `Status: ${load?.status ?? "-"}`,
    `Return path: ${requestedReturnTo ? "carried forward" : "default loads list"}`,
  ]), [load?.status, requestedReturnTo]);
  const operationalExceptionFlags = [
    (load?.status === "IN_TRANSIT" && isPastDay(load?.deliveryDate) ? "Late delivery" : null),
    ((load?.status === "AVAILABLE" || load?.status === "DRAFT") && (!load?.driver?.id || !load?.truck?.id) ? "Needs dispatch assignment" : null),
    (load?.status === "DELIVERED" ? "Awaiting invoice" : null),
    (load?.status === "INVOICED" && Number(load?.financialSummary?.outstandingAmount ?? 0) > 0 ? "Awaiting payment" : null),
  ].filter(Boolean) as string[];


  async function updateStatus() {
    if (!load) return;
    try {
      setWorking(true);
      await apiPost(`/api/loads/${load.id}/status`, { status: nextStatus });
      await loadRecord();
    } catch (err: any) {
      setError(err?.message ?? "Failed to update status");
    } finally {
      setWorking(false);
    }
  }

  async function runQuickStatus(status: string) {
    if (!load) return;
    try {
      setWorking(true);
      setNextStatus(status);
      await apiPost(`/api/loads/${load.id}/status`, { status });
      await loadRecord();
    } catch (err: any) {
      setError(err?.message ?? "Failed to update load lifecycle status");
    } finally {
      setWorking(false);
    }
  }

  async function createAccessorial(e: FormEvent) {
    e.preventDefault();
    if (!load) return;
    try {
      setAddingAccessorial(true);
      setError(null);
      await apiPost(`/api/loads/${load.id}/accessorials`, accessorialForm);
      setAccessorialForm({ category: "DETENTION", amount: "", description: "" });
      await loadRecord();
    } catch (err: any) {
      setError(err?.message ?? "Failed to add accessorial");
    } finally {
      setAddingAccessorial(false);
    }
  }

  async function createPayment(e: FormEvent) {
    e.preventDefault();
    if (!load) return;
    try {
      setAddingPayment(true);
      setError(null);
      await apiPost(`/api/loads/${load.id}/payments`, paymentForm);
      setPaymentForm({ paymentStatus: "UNPAID", invoiceNumber: getInvoiceNumber(load), invoiceDate: getInvoiceDate(load), amountDue: load.financialSummary?.grossRevenue || load.invoiceAmount || "", amountPaid: "", paidAt: "", paymentReference: "", notesText: "" });
      await loadRecord();
    } catch (err: any) {
      setError(err?.message ?? "Failed to add payment");
    } finally {
      setAddingPayment(false);
    }
  }

  async function markPayment(payment: LoadPayment, action: "paid" | "unpaid") {
    try {
      setWorking(true);
      setError(null);
      if (action === "paid") {
        await apiPost(`/api/load-payments/${payment.id}/mark-paid`, {
          amountPaid: payment.amountDue || payment.amountPaid || load?.financialSummary?.grossRevenue || load?.invoiceAmount || "",
          paymentReference: payment.paymentReference,
        });
      } else {
        await apiPost(`/api/load-payments/${payment.id}/mark-unpaid`, {});
      }
      await loadRecord();
    } catch (err: any) {
      setError(err?.message ?? `Failed to mark payment ${action}`);
    } finally {
      setWorking(false);
    }
  }

  if (error) {
    return <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>;
  }

  if (!load) {
    return <div className="text-sm text-gray-500">Loading load...</div>;
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={load.referenceNumber ? `Load ${load.referenceNumber}` : `Load ${load.id.slice(0, 8)}`}
        subtitle="Load record, status, route, money, paperwork, and next step."
        action={
          <div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:flex-wrap sm:justify-end">
            <Link href={resolvedReturnTo} className="w-full rounded-xl border bg-white px-4 py-2 text-center text-sm font-medium sm:w-auto">{requestedReturnTo ? "Return to queue" : "Back"}</Link>
            <Link href={appendReturnTo(`/loads/${load.id}/invoice`, requestedReturnTo)} className="w-full rounded-xl border bg-white px-4 py-2 text-center text-sm font-medium sm:w-auto">Invoice</Link>
            <Link href={appendReturnTo(`/loads/${load.id}/edit`, requestedReturnTo)} className="w-full rounded-xl bg-black px-4 py-2 text-center text-sm font-medium text-white sm:w-auto">Edit Load</Link>
          </div>
        }
      />

      <details className="group rounded-3xl border border-slate-200 bg-white shadow-sm">
        <summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-5 py-4">
          <div>
            <div className="text-sm font-semibold text-slate-900">Flow help and return path</div>
            <div className="mt-1 text-xs text-slate-500">Open this only when you need extra invoice, paperwork, or return-path help.</div>
          </div>
          <span className="rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[11px] font-medium text-slate-600 group-open:hidden">Show</span>
          <span className="hidden rounded-full border border-slate-200 bg-slate-900 px-2.5 py-1 text-[11px] font-medium text-white group-open:inline-flex">Hide</span>
        </summary>
        <div className="border-t border-slate-200 px-5 py-5 space-y-4">
      <WorkspaceHandoffPanel
        eyebrow="Load follow-through"
        title="This load now carries a clearer path into billing, documents, and back to the originating workflow."
        description="Use this page to move from dispatch work to paperwork, invoice work, and payment follow-up."
        badge={requestedReturnTo ? "Opened from a scoped queue" : "Opened directly from Loads"}
        links={[
          { label: requestedReturnTo ? "Return to queue" : "Back to loads", href: resolvedReturnTo },
          { label: "Edit in same flow", href: appendReturnTo(`/loads/${load.id}/edit`, requestedReturnTo) },
          { label: "Invoice in same flow", href: appendReturnTo(`/loads/${load.id}/invoice`, requestedReturnTo) },
          { label: "Ask CORI", href: `/cori?source=load-detail&returnTo=${encodeURIComponent(resolvedReturnTo)}&question=${encodeURIComponent(`What should I do next for load ${load.referenceNumber ?? load.id.slice(0, 8)}?`)}` },
        ]}
        cards={[
          {
            eyebrow: "Return path",
            title: requestedReturnTo ? "Go back to where you started" : "Return to Loads",
            detail: continuitySummary.join(" · "),
            href: resolvedReturnTo,
            cta: requestedReturnTo ? "Return to queue" : "Open loads",
          },
          {
            eyebrow: "Billing next step",
            title: load.status === "DELIVERED" || load.status === "INVOICED" ? "Move straight into invoice or payment follow-through" : "Billing path stays one click away",
            detail: "Keep invoice creation, receivables follow-up, and finance visibility attached to this load without rebuilding context.",
            href: appendReturnTo(`/loads/${load.id}/invoice`, requestedReturnTo),
            cta: "Open invoice flow",
          },
          {
            eyebrow: "Paperwork proof",
            title: "Open paperwork proof from this record",
            detail: "Open the Paperwork page when proof is missing or needs to be linked.",
            href: appendReturnTo(`/documents?source=load-detail&loadId=${load.id}`, requestedReturnTo),
            cta: "Open paperwork",
          },
          {
            eyebrow: "Dispatch next step",
            title: "Return to the Dispatch Board with this load",
            detail: "Use this when the record work is finished and the load needs to move back into dispatch execution or board review.",
            href: appendReturnTo(`/dispatch?highlightLoad=${load.id}`, requestedReturnTo),
            cta: "Open dispatch",
          },
        ]}
      />

      <UniversalQuickActions
        title="Move this load through the next operational step"
        subtitle="Use load detail as the quick-action bridge between dispatch execution, proof follow-through, invoicing, and the return path back to where you came from."
        actions={[
          { label: requestedReturnTo ? "Return to queue" : "Return to loads", href: resolvedReturnTo, detail: requestedReturnTo ? "Go back to the exact scoped queue you opened this load from." : "Return to the broader loads workspace.", emphasis: "subtle" },
          { label: "Dispatch", href: appendReturnTo(`/dispatch?highlightLoad=${load.id}`, requestedReturnTo), detail: "Reopen dispatch execution with this load still highlighted.", emphasis: "primary" },
          { label: "Billing / invoice", href: appendReturnTo(`/loads/${load.id}/invoice`, requestedReturnTo), detail: "Move this record into invoice creation or payment follow-through." },
          { label: "Documents", href: appendReturnTo(`/documents?source=load-detail-quick-actions&loadId=${load.id}`, requestedReturnTo), detail: "Open document relink, proof, and compliance work for this load." },
        ]}
      />

        </div>
      </details>

      <section className="rounded-3xl border bg-white p-5 shadow-sm">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div className="max-w-2xl">
            <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">Load now</div>
            <h3 className="mt-2 text-lg font-semibold text-slate-900">Keep the status, lane, and next move at the top</h3>
            <p className="mt-1 text-sm text-slate-600">The first screen should answer three things fast: what this load is, where it is going, and what dispatch should do next.</p>
          </div>
        </div>

        <div className="mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Status</div>
              <div className="mt-2 text-sm font-semibold text-slate-900">{load.status.replaceAll('_', ' ')}</div>
              <div className="mt-1 text-sm text-slate-600">Visible before the deeper detail blocks.</div>
            </div>
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Lane</div>
              <div className="mt-2 text-sm font-semibold text-slate-900">{`${load.pickupLocation || 'Pickup'} → ${load.deliveryLocation || 'Delivery'}`}</div>
              <div className="mt-1 text-sm text-slate-600">Quick lane read for calls and follow-up.</div>
            </div>
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Next move</div>
              <div className="mt-2 text-sm font-semibold text-slate-900">{getNextOperationalAction(load)}</div>
              <div className="mt-1 text-sm text-slate-600">The main action reason stays close to the top.</div>
            </div>
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Open balance</div>
              <div className="mt-2 text-sm font-semibold text-slate-900">{money(openBalance)}</div>
              <div className="mt-1 text-sm text-slate-600">Billing pressure stays visible without scrolling.</div>
            </div>
          </div>
      </section>

      <section className="rounded-3xl border bg-white p-5 shadow-sm">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div className="max-w-2xl">
            <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">Call entry</div>
            <h3 className="mt-2 text-lg font-semibold text-slate-900">Keep the main load call actions close to the top</h3>
            <p className="mt-1 text-sm text-slate-600">When dispatch needs an update, the driver and broker call paths should be easy to reach without hunting through the page.</p>
          </div>
          <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Driver</div>
              <div className="mt-2 text-sm font-semibold text-slate-900">{assignedDriver ? [assignedDriver.firstName, assignedDriver.lastName].filter(Boolean).join(" ") : load.driver?.firstName || "Not assigned"}</div>
              <div className="mt-1 text-sm text-slate-600">{assignedDriver?.phone ? assignedDriver.phone : assignedDriver ? "Phone missing on driver record." : "Assign a driver for faster check calls."}</div>
            </div>
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Broker</div>
              <div className="mt-2 text-sm font-semibold text-slate-900">{load.broker?.name || "No broker linked"}</div>
              <div className="mt-1 text-sm text-slate-600">{load.broker?.phone ? load.broker.phone : "Broker phone will fill here when available."}</div>
            </div>
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Lane</div>
              <div className="mt-2 text-sm font-semibold text-slate-900">{`${load.pickupLocation || "Pickup"} → ${load.deliveryLocation || "Delivery"}`}</div>
              <div className="mt-1 text-sm text-slate-600">CORI can carry this lane context into the call surface.</div>
            </div>
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Next move</div>
              <div className="mt-2 text-sm font-semibold text-slate-900">{getNextOperationalAction(load)}</div>
              <div className="mt-1 text-sm text-slate-600">Keep the call reason close to the launch buttons.</div>
            </div>
          </div>
        </div>

        <div className="mt-4 flex flex-wrap gap-2">
          {assignedDriver?.phone ? (
            <CallCopilotLink
              context={{
                source: "load-detail-driver",
                contactId: assignedDriver.id,
                contactType: "driver",
                contactName: [assignedDriver.firstName, assignedDriver.lastName].filter(Boolean).join(" ") || "Driver",
                phone: assignedDriver.phone || undefined,
                companyLabel: assignedDriver.companyName || "Assigned driver",
                truckLabel: load.truck?.truckNumber ? `Truck ${load.truck.truckNumber}` : undefined,
                laneLabel: `${load.pickupLocation || "Pickup"} → ${load.deliveryLocation || "Delivery"}`,
                purpose: load.status === "IN_TRANSIT" ? "ETA_UPDATE" : "CHECK_LOAD_DETAILS",
              }}
              className="inline-flex rounded-xl bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700"
            >
              Call driver
            </CallCopilotLink>
          ) : assignedDriver ? (
            <Link href={`/drivers/${assignedDriver.id}`} className="inline-flex rounded-xl border border-amber-200 bg-amber-50 px-4 py-2 text-sm font-medium text-amber-800">Add driver phone</Link>
          ) : null}

          {load.broker ? (
            <CallCopilotLink
              context={{
                source: "load-detail-broker",
                contactId: load.broker.id,
                contactType: "broker",
                contactName: load.broker.name,
                phone: load.broker.phone || undefined,
                companyLabel: load.broker.name,
                truckLabel: load.truck?.truckNumber ? `Truck ${load.truck.truckNumber}` : undefined,
                laneLabel: `${load.pickupLocation || "Pickup"} → ${load.deliveryLocation || "Delivery"}`,
                floorRate: load.invoiceAmount || undefined,
                purpose: load.status === "AVAILABLE" ? "NEGOTIATE_RATE" : "CHECK_LOAD_DETAILS",
              }}
              className="inline-flex rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700"
            >
              Call broker
            </CallCopilotLink>
          ) : null}

          <Link href={`/cori?source=load-detail&question=${encodeURIComponent(`What is the next best move for load ${load.referenceNumber ?? load.id.slice(0, 8)}?`)}`} className="inline-flex rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700">Ask CORI what to do next</Link>
          <Link href={appendReturnTo(`/dispatch?highlightLoad=${load.id}`, requestedReturnTo)} className="inline-flex rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700">Open dispatch with this load</Link>
        </div>
      </section>

      <details className="group rounded-3xl border border-slate-200 bg-white shadow-sm">
        <summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-5 py-4">
          <div>
            <div className="text-sm font-semibold text-slate-900">More load tools</div>
            <div className="mt-1 text-xs text-slate-500">Open this when you need the wider dispatch, billing, and document shortcuts.</div>
          </div>
          <span className="rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[11px] font-medium text-slate-600 group-open:hidden">Show</span>
          <span className="hidden rounded-full border border-slate-200 bg-slate-900 px-2.5 py-1 text-[11px] font-medium text-white group-open:inline-flex">Hide</span>
        </summary>
        <div className="border-t border-slate-200 px-5 py-5 space-y-4">
      <section className="grid gap-3 xl:grid-cols-4">
        <div className="rounded-2xl border bg-slate-50 p-4 shadow-sm">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Action rail</div>
          <div className="mt-2 text-sm font-semibold text-slate-900">Open the next workspace without losing this load.</div>
          <div className="mt-2 text-xs text-slate-600">Treat load detail as the hub between dispatch, documents, and finance work.</div>
        </div>
        <Link href={appendReturnTo(`/dispatch?highlightLoad=${load.id}`, requestedReturnTo)} className="rounded-2xl border bg-white p-4 shadow-sm transition hover:-translate-y-0.5 hover:border-slate-300">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Dispatch</div>
          <div className="mt-2 text-sm font-semibold text-slate-900">Send this back into execution</div>
          <div className="mt-1 text-xs text-slate-500">Reopen the dispatch board with this load still in mind.</div>
        </Link>
        <Link href={appendReturnTo(`/billing?source=load-detail&loadId=${load.id}`, requestedReturnTo)} className="rounded-2xl border bg-white p-4 shadow-sm transition hover:-translate-y-0.5 hover:border-slate-300">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Billing</div>
          <div className="mt-2 text-sm font-semibold text-slate-900">Continue into invoice and payment follow-through</div>
          <div className="mt-1 text-xs text-slate-500">Use this when the load is ready for invoice or collections work.</div>
        </Link>
        <Link href={appendReturnTo(`/documents?source=load-detail&loadId=${load.id}`, requestedReturnTo)} className="rounded-2xl border bg-white p-4 shadow-sm transition hover:-translate-y-0.5 hover:border-slate-300">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Documents</div>
          <div className="mt-2 text-sm font-semibold text-slate-900">Work missing proof and compliance follow-through</div>
          <div className="mt-1 text-xs text-slate-500">Jump into missing document review without abandoning this record path.</div>
        </Link>
      </section>



      <section className="grid gap-3 xl:grid-cols-3">
        <div className="rounded-2xl border bg-slate-50 p-4 shadow-sm">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Document relink</div>
          <div className="mt-2 text-sm font-semibold text-slate-900">Resolve proof exceptions without abandoning this load.</div>
          <div className="mt-1 text-xs text-slate-500">Use the document workspace when the package needs relink, missing-proof review, or fast CORI guidance.</div>
        </div>
        <Link href={appendReturnTo(`/documents?source=load-detail&loadId=${load.id}&focus=relink`, requestedReturnTo)} className="rounded-2xl border bg-white p-4 shadow-sm transition hover:-translate-y-0.5 hover:border-slate-300">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Relink workflow</div>
          <div className="mt-2 text-sm font-semibold text-slate-900">Open document relink for this load</div>
          <div className="mt-1 text-xs text-slate-500">Jump straight into the documents workspace with this load carried into the relink path.</div>
        </Link>
        <Link href={`/cori?source=load-detail&returnTo=${encodeURIComponent(resolvedReturnTo)}&question=${encodeURIComponent(`Turn the document blockers on load ${load.referenceNumber ?? load.id.slice(0, 8)} into a short operator action list.`)}`} className="rounded-2xl border bg-white p-4 shadow-sm transition hover:-translate-y-0.5 hover:border-slate-300">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Exception shortcut</div>
          <div className="mt-2 text-sm font-semibold text-slate-900">Generate a document-resolution action list</div>
          <div className="mt-1 text-xs text-slate-500">Use CORI to turn the visible document blockers into a short next-step checklist.</div>
        </Link>
      </section>

        </div>
      </details>
      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <MetricCard label="Status" value={<StatusPill status={load.status} />} />
        <MetricCard label="Broker" value={load.broker?.name} />
        <MetricCard label="Truck" value={load.truck?.truckNumber} />
        <MetricCard label="Driver" value={[load.driver?.firstName, load.driver?.lastName].filter(Boolean).join(" ")} />
      </div>

      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <MetricCard label="Invoice Total" value={money(load.financialSummary?.grossRevenue)} />
        <MetricCard label="Gross Margin" value={money(load.financialSummary?.grossMargin)} />
        <MetricCard label="Amount Paid" value={money(load.financialSummary?.amountPaidTotal)} />
        <MetricCard label="Outstanding" value={money(load.financialSummary?.outstandingAmount)} />
      </div>

      <Card title="Operational execution">
        <div className="grid gap-4 lg:grid-cols-[1.4fr_1fr]">
          <div className="space-y-3">
            <div className="rounded-xl border bg-slate-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Next action</div>
              <div className="mt-2 text-base font-semibold text-slate-900">{getNextOperationalAction(load)}</div>
              <div className="mt-2 flex flex-wrap gap-2 text-xs text-slate-600">
                <span>Pickup: {sameDay(load.pickupDate) ? "Today" : dateTime(load.pickupDate)}</span>
                <span>Delivery: {sameDay(load.deliveryDate) ? "Today" : dateTime(load.deliveryDate)}</span>
                <span>Check-call: {load.status === "IN_TRANSIT" ? "Visible / due" : "Not required"}</span>
              </div>
            </div>

            <div className="flex flex-wrap gap-2">
              {getQuickStatusActions(load).map((action) => (
                <button key={action.status} onClick={() => runQuickStatus(action.status)} disabled={working} className="rounded-xl border bg-white px-3 py-2 text-sm font-medium disabled:opacity-60">
                  {action.label}
                </button>
              ))}
              <Link href={appendReturnTo(`/loads/${load.id}/invoice`, requestedReturnTo)} className="rounded-xl border bg-white px-3 py-2 text-sm font-medium">Invoice page</Link>
            </div>
          </div>

          <div className="rounded-xl border bg-white p-4">
            <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Operational exception flags</div>
            <div className="mt-3 space-y-2">
              {operationalExceptionFlags.length ? operationalExceptionFlags.map((flag) => (
                <div key={flag} className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">{flag}</div>
              )) : (
                <div className="rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-700">No active operational exceptions on this load.</div>
              )}
            </div>
          </div>
        </div>
      </Card>

      <AssignmentPanel targetType="LOAD" targetId={load.id} targetLabel="load" />

      <div className="grid gap-6 xl:grid-cols-2">
        <Card title="Assignment">
          <Row label="Status" value={load.status} />
          <Row label="Broker" value={load.broker?.name} />
          <Row label="Truck" value={load.truck?.truckNumber} />
          <Row label="Driver" value={[load.driver?.firstName, load.driver?.lastName].filter(Boolean).join(" ")} />
        </Card>

        <Card title="Route">
          <Row label="Pickup" value={load.pickupLocation} />
          <Row label="Delivery" value={load.deliveryLocation} />
          <Row label="Pickup date" value={dateTime(load.pickupDate)} />
          <Row label="Delivery date" value={dateTime(load.deliveryDate)} />
        </Card>

        <Card title="Load financials">
          <Row label="Base rate" value={money(load.invoiceAmount)} />
          <Row label="Accessorial total" value={money(load.financialSummary?.accessorialTotal)} />
          <Row label="Invoice total" value={money(load.financialSummary?.grossRevenue)} />
          <Row label="Dispatch fee" value={money(load.financialSummary?.dispatchFeeAmount)} />
          <Row label="Driver pay" value={money(load.financialSummary?.driverPayAmount)} />
          <Row label="Gross margin" value={money(load.financialSummary?.grossMargin)} />
          <Row label="Amount paid" value={money(load.financialSummary?.amountPaidTotal)} />
          <Row label="Outstanding" value={money(load.financialSummary?.outstandingAmount)} />
          <Row label="Payment status" value={load.financialSummary?.paymentStatusSummary} />
        </Card>

        <Card title="References">
          <Row label="Reference number" value={load.referenceNumber} />
          <Row label="Rate confirmation #" value={load.rateConfirmationNumber} />
          <Row label="Miles" value={load.miles} />
          <Row label="Rate per mile" value={money(load.ratePerMile)} />
          <Row label="Special requirements" value={load.specialRequirements} />
        </Card>
      </div>

      <Card title="Status control" action={<StatusPill status={load.status} />}>
        <div className="flex flex-col gap-3 lg:flex-row lg:items-center">
          <select value={nextStatus} onChange={(e) => setNextStatus(e.target.value)} className="w-full rounded-xl border bg-white px-3 py-2 text-sm lg:max-w-xs">
            <option value="DRAFT">Draft</option>
            <option value="ASSIGNED">Assigned</option>
            <option value="IN_TRANSIT">In Transit</option>
            <option value="DELIVERED">Delivered</option>
            <option value="INVOICED">Invoiced</option>
            <option value="PAID_FULL">Paid in full</option>
            <option value="CANCELLED">Cancelled</option>
          </select>
          <button onClick={updateStatus} disabled={working} className="w-full rounded-xl bg-black px-4 py-2 text-sm font-medium text-white disabled:opacity-60 lg:w-auto">
            {working ? "Updating..." : "Update status"}
          </button>
        </div>
      </Card>

      <div className="grid gap-6 xl:grid-cols-2">
        <LoadBillingReadinessPanel load={load} />
        <LoadsDocumentCompliancePanel load={load} />
      </div>

      <LoadsDocumentIntakePanel
        load={load}
        editHref={appendReturnTo(`/loads/${load.id}/edit`, requestedReturnTo)}
        invoiceHref={appendReturnTo(`/loads/${load.id}/invoice`, requestedReturnTo)}
      />

      <AssignmentComplianceReadinessPanel
        load={load}
        driver={assignedDriver}
        truck={assignedTruck}
        editHref={appendReturnTo(`/loads/${load.id}/edit`, requestedReturnTo)}
      />

      <LoadDocumentAccessPanel load={load} driver={assignedDriver} truck={assignedTruck} />

      {documentLifecycle ? <DocumentLifecycleUnification snapshot={documentLifecycle} returnTo={resolvedReturnTo} compact /> : null}

      <div className="grid gap-6 xl:grid-cols-2">
        <Card title="Accessorials" action={<div className="text-sm text-gray-500">Total {money(load.financialSummary?.accessorialTotal)}</div>}>
          <form onSubmit={createAccessorial} className="mb-5 grid gap-3 rounded-xl border p-4 md:grid-cols-2 xl:grid-cols-4">
            <Field label="Category">
              <Select value={accessorialForm.category} onChange={(e) => setAccessorialForm((current) => ({ ...current, category: e.target.value }))}>
                <option value="DETENTION">Detention</option>
                <option value="LAYOVER">Layover</option>
                <option value="TONU">TONU</option>
                <option value="OTHER">Other</option>
              </Select>
            </Field>
            <Field label="Amount">
              <Input value={accessorialForm.amount} onChange={(e) => setAccessorialForm((current) => ({ ...current, amount: e.target.value }))} />
            </Field>
            <Field label="Description" >
              <Input value={accessorialForm.description} onChange={(e) => setAccessorialForm((current) => ({ ...current, description: e.target.value }))} />
            </Field>
            <div className="flex items-end md:col-span-2 xl:col-span-1">
              <button type="submit" disabled={addingAccessorial} className="w-full rounded-xl border bg-white px-4 py-2 text-sm font-medium disabled:opacity-60">
                {addingAccessorial ? "Adding..." : "Add accessorial"}
              </button>
            </div>
          </form>

          {accessorials.length ? (
            <div className="space-y-3">
              {accessorials.map((item: LoadAccessorial) => (
                <div key={item.id} className="rounded-xl border px-4 py-3 text-sm">
                  <div className="flex items-center justify-between gap-4">
                    <div>
                      <div className="font-medium">{item.category}</div>
                      <div className="text-gray-500">{item.description || "No description"}</div>
                    </div>
                    <div className="text-right font-medium">{money(item.amount)}</div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-sm text-gray-500">No accessorials recorded yet.</div>
          )}
        </Card>

        <Card title="Broker payments" action={<div className="text-sm text-gray-500">Open balance {money(openBalance)}</div>}>
          <form onSubmit={createPayment} className="mb-5 grid gap-3 rounded-xl border p-4 lg:grid-cols-2">
            <Field label="Payment status">
              <Select value={paymentForm.paymentStatus} onChange={(e) => setPaymentForm((current) => ({ ...current, paymentStatus: e.target.value }))}>
                <option value="UNPAID">Unpaid</option>
                <option value="PARTIAL">Partial</option>
                <option value="PAID">Paid</option>
              </Select>
            </Field>
            <Field label="Invoice #">
              <Input value={paymentForm.invoiceNumber} onChange={(e) => setPaymentForm((current) => ({ ...current, invoiceNumber: e.target.value }))} />
            </Field>
            <Field label="Invoice date">
              <Input type="date" value={paymentForm.invoiceDate} onChange={(e) => setPaymentForm((current) => ({ ...current, invoiceDate: e.target.value }))} />
            </Field>
            <Field label="Amount due">
              <Input value={paymentForm.amountDue} onChange={(e) => setPaymentForm((current) => ({ ...current, amountDue: e.target.value }))} />
            </Field>
            <Field label="Amount paid">
              <Input value={paymentForm.amountPaid} onChange={(e) => setPaymentForm((current) => ({ ...current, amountPaid: e.target.value }))} />
            </Field>
            <Field label="Paid date">
              <Input type="date" value={paymentForm.paidAt} onChange={(e) => setPaymentForm((current) => ({ ...current, paidAt: e.target.value }))} />
            </Field>
            <Field label="Payment reference">
              <Input value={paymentForm.paymentReference} onChange={(e) => setPaymentForm((current) => ({ ...current, paymentReference: e.target.value }))} />
            </Field>
            <Field label="Notes">
              <TextArea rows={3} value={paymentForm.notesText} onChange={(e) => setPaymentForm((current) => ({ ...current, notesText: e.target.value }))} />
            </Field>
            <div className="lg:col-span-2 flex justify-stretch lg:justify-end">
              <button type="submit" disabled={addingPayment} className="w-full rounded-xl border bg-white px-4 py-2 text-sm font-medium disabled:opacity-60 lg:w-auto">
                {addingPayment ? "Adding..." : "Add payment record"}
              </button>
            </div>
          </form>

          {payments.length ? (
            <div className="space-y-3">
              {payments.map((payment) => (
                <div key={payment.id} className="rounded-xl border px-4 py-3 text-sm">
                  <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
                    <div className="space-y-1">
                      <div className="font-medium">{payment.invoiceNumber || "Payment record"}</div>
                      <div className="text-gray-500">Status: {payment.paymentStatus}</div>
                      <div className="text-gray-500">Invoice date: {payment.invoiceDate ? dateTime(payment.invoiceDate) : "-"}</div>
                      <div className="text-gray-500">Reference: {payment.paymentReference || "-"}</div>
                      {payment.notesText ? <div className="text-gray-700">{payment.notesText}</div> : null}
                    </div>
                    <div className="space-y-1 text-left lg:text-right">
                      <div>Due: <span className="font-medium">{money(payment.amountDue)}</span></div>
                      <div>Paid: <span className="font-medium">{money(payment.amountPaid)}</span></div>
                      <div className="text-gray-500">Paid at: {payment.paidAt ? dateTime(payment.paidAt) : "-"}</div>
                      <div className="flex flex-wrap justify-start gap-2 pt-2 lg:justify-end">
                        {payment.paymentStatus === "PAID" ? (
                          <button onClick={() => markPayment(payment, "unpaid")} disabled={working} className="rounded-lg border px-3 py-1.5 text-xs font-medium">
                            Mark unpaid
                          </button>
                        ) : (
                          <button onClick={() => markPayment(payment, "paid")} disabled={working} className="rounded-lg bg-black px-3 py-1.5 text-xs font-medium text-white">
                            Mark paid
                          </button>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-sm text-gray-500">No payment records recorded yet.</div>
          )}
        </Card>
      </div>

      <Card title="Status history">
        {load.statusHistory?.length ? (
          <div className="space-y-3">
            {load.statusHistory.map((item) => (
              <div key={item.id} className="rounded-xl border px-4 py-3 text-sm">
                <div className="font-medium">{item.fromStatus ? `${item.fromStatus} → ${item.toStatus}` : item.toStatus}</div>
                <div className="text-gray-500">{new Date(item.changedAt).toLocaleString()}</div>
                {item.note ? <div className="mt-1 text-gray-700">{item.note}</div> : null}
              </div>
            ))}
          </div>
        ) : (
          <div className="text-sm text-gray-500">No status history recorded yet.</div>
        )}
      </Card>

      <Card title="Notes">
        <div className="whitespace-pre-wrap text-sm text-gray-700">{load.notesText || "No notes recorded."}</div>
      </Card>
    </div>
  );
}
