"use client";

import Link from "next/link";
import type { Load } from "@/types";
import { getLoadDocumentIntakeState } from "@/components/loads-document-intake-panel";

function driverName(load: Load) {
  const parts = [load.driver?.firstName, load.driver?.lastName].filter(Boolean);
  return parts.length ? parts.join(" ") : null;
}

function routeLabel(load: Load) {
  if (load.pickupLocation && load.deliveryLocation) return `${load.pickupLocation} to ${load.deliveryLocation}`;
  return load.pickupLocation || load.deliveryLocation || null;
}

function loadContext(load: Load) {
  const parts = [] as string[];
  if (load.truck?.truckNumber) parts.push(`Truck ${load.truck.truckNumber}`);
  const name = driverName(load);
  if (name) parts.push(name);
  const route = routeLabel(load);
  if (route) parts.push(route);
  return parts.join(" · ") || `Load ${load.referenceNumber || load.id.slice(0, 8)}`;
}

function Lane({ title, description, rows }: { title: string; description: string; rows: Array<{ load: Load; prompt: string }> }) {
  return (
    <div className="rounded-2xl border bg-white p-4 shadow-sm">
      <div className="mb-3">
        <div className="text-sm font-semibold text-slate-900">{title}</div>
        <div className="mt-1 text-xs text-slate-500">{description}</div>
      </div>

      <div className="space-y-2">
        {rows.length ? rows.slice(0, 4).map(({ load, prompt }) => (
          <Link key={load.id} href={`/loads/${load.id}`} className="block rounded-xl border border-slate-200 bg-slate-50 px-3 py-3 hover:bg-slate-100">
            <div className="text-sm font-medium text-slate-900">Documents still needed</div>
            <div className="mt-1 text-xs text-slate-600">{loadContext(load)}</div>
            <div className="mt-1 text-xs text-slate-500">Load: {load.referenceNumber || load.id.slice(0, 8)}</div>
            <div className="mt-2 text-xs text-slate-700">{prompt}</div>
          </Link>
        )) : (
          <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-3 text-sm text-emerald-700">No loads are currently sitting in this paperwork lane.</div>
        )}
      </div>
    </div>
  );
}

export function DispatchDocumentLifecycleQueue({ loads }: { loads: Load[] }) {
  const activeLoads = loads.filter((load) => ["AVAILABLE", "ASSIGNED", "IN_TRANSIT", "DELIVERED", "INVOICED", "PAID_FULL"].includes(load.status));

  const missingBrokerIntake = activeLoads
    .map((load) => ({ load, state: getLoadDocumentIntakeState(load) }))
    .filter(({ load, state }) => ["AVAILABLE", "ASSIGNED", "IN_TRANSIT"].includes(load.status) && state.documentCapturePrompts.some((prompt) => prompt.toLowerCase().includes("broker") || prompt.toLowerCase().includes("rate confirmation")))
    .map(({ load, state }) => ({ load, prompt: state.nextAction }));

  const deliveredDocCapture = activeLoads
    .map((load) => ({ load, state: getLoadDocumentIntakeState(load) }))
    .filter(({ load, state }) => ["DELIVERED", "INVOICED"].includes(load.status) && state.documentCapturePrompts.some((prompt) => prompt.toLowerCase().includes("pod") || prompt.toLowerCase().includes("invoice")))
    .map(({ load, state }) => ({ load, prompt: state.nextAction }));

  const closeoutProof = activeLoads
    .map((load) => ({ load, state: getLoadDocumentIntakeState(load) }))
    .filter(({ load, state }) => load.status === "PAID_FULL" && state.documentCapturePrompts.some((prompt) => prompt.toLowerCase().includes("payment reference") || prompt.toLowerCase().includes("closeout")))
    .map(({ load, state }) => ({ load, prompt: state.nextAction }));

  return (
    <section className="space-y-4">
      <div className="rounded-2xl border bg-white p-5 shadow-sm">
        <div className="text-base font-semibold text-slate-900">Operator-ready document queue refinement</div>
        <div className="mt-1 text-sm text-slate-600">Focused document lanes for broker intake, delivery package completion, invoice-package completeness, and final closeout proof.</div>
      </div>

      <div className="grid gap-4 xl:grid-cols-2 2xl:grid-cols-4">
        <Lane title="Broker intake follow-up" description="Active loads missing a broker contact path or a visible rate-con anchor." rows={missingBrokerIntake} />
        <Lane title="Delivery document capture" description="Delivered or invoiced loads that still need POD or invoice notes." rows={deliveredDocCapture} />
        <Lane title="Invoice package completeness" description="Delivered or invoiced loads that still need the final delivery-to-billing document package tightened." rows={deliveredDocCapture.filter(({ prompt }) => prompt.toLowerCase().includes("invoice") || prompt.toLowerCase().includes("pod"))} />
        <Lane title="Closeout proof follow-up" description="Paid loads that still need a visible payment reference for clean documentary closeout." rows={closeoutProof} />
      </div>
    </section>
  );
}
