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

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 isPast(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);
}

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

export function DispatchExceptionFollowUpQueue({ loads, returnTo }: { loads: Load[]; returnTo?: string }) {
  const lanes: Lane[] = [
    {
      key: "late-delivery",
      label: "Late-delivery exceptions",
      description: "In-transit loads whose delivery date is already behind today.",
      tone: "border-red-200 bg-red-50 text-red-800",
      filters: { status: "IN_TRANSIT" },
      loads: loads.filter((load) => load.status === "IN_TRANSIT" && isPast(load.deliveryDate)).slice(0, 5),
      actionLabel: "Resolve ETA",
    },
    {
      key: "pickup-today",
      label: "Pickup windows today",
      description: "Assigned or available loads with live pickup timing today.",
      tone: "border-blue-200 bg-blue-50 text-blue-800",
      filters: { pickupFrom: new Date().toISOString().slice(0, 10), pickupTo: new Date().toISOString().slice(0, 10) },
      loads: loads.filter((load) => (load.status === "AVAILABLE" || load.status === "ASSIGNED") && sameDay(load.pickupDate)).slice(0, 5),
      actionLabel: "Confirm dispatch out",
    },
    {
      key: "delivered-awaiting-invoice",
      label: "Delivered awaiting invoice",
      description: "Loads ready for billing before paperwork gets stale.",
      tone: "border-yellow-200 bg-yellow-50 text-yellow-800",
      filters: { uninvoiced: true },
      loads: loads.filter((load) => load.status === "DELIVERED").slice(0, 5),
      actionLabel: "Move to invoice",
    },
    {
      key: "collections",
      label: "Payment follow-up",
      description: "Invoiced loads that still show open balance exposure.",
      tone: "border-purple-200 bg-purple-50 text-purple-800",
      filters: { status: "INVOICED", unpaid: true },
      loads: loads.filter((load) => load.status === "INVOICED" && Number(load.financialSummary?.outstandingAmount ?? 0) > 0).slice(0, 5),
      actionLabel: "Follow up",
    },
  ].filter((lane) => lane.loads.length > 0);

  if (!lanes.length) {
    return (
      <section className="rounded-2xl border bg-white p-5 shadow-sm">
        <div className="text-sm font-semibold text-slate-900">Dispatcher exception follow-up queue</div>
        <div className="mt-2 rounded-xl border border-dashed px-4 py-6 text-sm text-slate-500">No active exception or follow-up lanes need dispatcher action right now.</div>
      </section>
    );
  }

  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">Dispatcher exception follow-up queue</div>
          <div className="text-xs text-slate-500">A tighter action queue for the records most likely to fall out of control without same-day dispatcher follow-up.</div>
        </div>
      </div>

      <div className="mt-4 grid gap-4 xl:grid-cols-2">
        {lanes.map((lane) => {
          const queueHref = `/loads?${buildLoadListQuery(lane.filters)}`;
          return (
            <div key={lane.key} className={`rounded-2xl border p-4 ${lane.tone}`}>
              <div className="flex flex-wrap items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold">{lane.label}</div>
                  <div className="mt-1 text-xs opacity-80">{lane.description}</div>
                </div>
                <Link href={queueHref} className="rounded-xl border bg-white px-3 py-2 text-xs font-semibold text-slate-800">
                  Open filtered queue
                </Link>
              </div>
              <div className="mt-3 space-y-2">
                {lane.loads.map((load) => (
                  <div key={load.id} className="rounded-xl border border-white/70 bg-white/80 px-3 py-3 text-slate-900">
                    <div className="flex flex-wrap items-start justify-between gap-3">
                      <div>
                        <div className="text-sm font-semibold">{load.referenceNumber || load.id.slice(0, 8)}</div>
                        <div className="mt-1 text-xs text-slate-600">{load.pickupLocation || "-"} → {load.deliveryLocation || "-"}</div>
                      </div>
                      <Link href={returnTo ? appendReturnTo(`/loads/${load.id}`, returnTo) : `/loads/${load.id}`} className="text-xs font-semibold text-slate-800 hover:underline">
                        {lane.actionLabel}
                      </Link>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}
