"use client";

import Link from "next/link";
import type { Load } from "@/types";
import { appendReturnTo } from "@/src/modules/loads/load-navigation";

function isSameDay(value?: string | null) {
  if (!value) return false;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return false;
  const now = new Date();
  return date.getFullYear() === now.getFullYear() && date.getMonth() === now.getMonth() && date.getDate() === now.getDate();
}

function isPast(value?: string | null) {
  if (!value) return false;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return false;
  return date.getTime() < Date.now();
}

export function DispatchExecutionAudit({ loads, returnTo }: { loads: Load[]; returnTo?: string }) {
  const assignmentPressure = loads.filter((load) => (load.status === "DRAFT" || load.status === "AVAILABLE") && (!load.truck?.id || !load.driver?.id));
  const stagedButThin = loads.filter((load) => load.status === "ASSIGNED" && (!load.truck?.id || !load.driver?.id));
  const pickupsToday = loads.filter((load) => isSameDay(load.pickupDate) && (load.status === "DRAFT" || load.status === "AVAILABLE" || load.status === "ASSIGNED"));
  const movementExceptions = loads.filter((load) => load.status === "IN_TRANSIT" && isPast(load.deliveryDate));
  const deliveredWaitingInvoice = loads.filter((load) => load.status === "DELIVERED");
  const overdueCheckCalls = loads.filter((load) => load.status === "IN_TRANSIT" && isPast(load.pickupDate) && !isSameDay(load.deliveryDate));

  const urgentCount = assignmentPressure.length + movementExceptions.length + pickupsToday.filter((load) => !load.truck?.id || !load.driver?.id).length;
  const watchCount = stagedButThin.length + deliveredWaitingInvoice.length + overdueCheckCalls.length;
  const status = urgentCount ? { label: "Work items need attention", tone: "border-red-200 bg-red-50 text-red-700" } : watchCount ? { label: "Work needs review", tone: "border-amber-200 bg-amber-50 text-amber-700" } : { label: "Work looks aligned", tone: "border-emerald-200 bg-emerald-50 text-emerald-700" };

  const focusCards = [
    {
      key: "assignment",
      label: "Assignment lane first",
      value: assignmentPressure.length,
      detail: assignmentPressure.length ? "Available work still needs truck and driver coverage." : "No visible available work is waiting on basic assignment coverage.",
      href: "/dispatch?unassigned=true",
      cta: "Open assignment queue",
      tone: "border-blue-200 bg-blue-50",
    },
    {
      key: "today",
      label: "Move today’s freight",
      value: pickupsToday.length,
      detail: pickupsToday.length ? "Loads touching today still need close dispatcher attention." : "No visible pickup-today pressure is building right now.",
      href: "/dispatch?status=AVAILABLE",
      cta: "Open today queue",
      tone: "border-indigo-200 bg-indigo-50",
    },
    {
      key: "movement",
      label: "Movement exceptions",
      value: movementExceptions.length,
      detail: movementExceptions.length ? "In-transit work is running past the planned delivery date." : "No visible overdue movement exceptions in the board.",
      href: "/dispatch?status=IN_TRANSIT",
      cta: "Open movement lane",
      tone: "border-rose-200 bg-rose-50",
    },
    {
      key: "closeout",
      label: "Closeout step",
      value: deliveredWaitingInvoice.length,
      detail: deliveredWaitingInvoice.length ? "Delivered work is waiting to convert into billing." : "Delivered closeout pressure is currently under control.",
      href: "/dispatch?status=DELIVERED&uninvoiced=true",
      cta: "Open invoice queue",
      tone: "border-amber-200 bg-amber-50",
    },
  ] as const;

  const prompts = [
    assignmentPressure.length ? `${assignmentPressure.length} visible loads still need truck or driver coverage.` : null,
    stagedButThin.length ? `${stagedButThin.length} assigned loads still need coverage details.` : null,
    movementExceptions.length ? `${movementExceptions.length} in-transit loads are running past planned delivery timing.` : null,
    deliveredWaitingInvoice.length ? `${deliveredWaitingInvoice.length} delivered loads still need billing follow-up.` : null,
    overdueCheckCalls.length ? `${overdueCheckCalls.length} moving loads likely need a fresh dispatcher check call.` : null,
  ].filter(Boolean) as string[];

  return (
    <section className="rounded-2xl border bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-slate-900">Dispatch check</div>
          <div className="text-xs text-slate-500">A quick check of assignments, moving loads, and closeout work before you work the board.</div>
        </div>
        <div className={`rounded-full border px-3 py-1 text-xs font-semibold ${status.tone}`}>{status.label}</div>
      </div>

      <div className="mt-4 grid gap-3 xl:grid-cols-4">
        {focusCards.map((card) => (
          <div key={card.key} className={`rounded-xl border p-4 ${card.tone}`}>
            <div className="flex items-center justify-between gap-3">
              <div className="text-sm font-semibold text-slate-900">{card.label}</div>
              <div className="rounded-full bg-white px-2 py-0.5 text-xs font-semibold text-slate-700">{card.value}</div>
            </div>
            <div className="mt-2 text-xs leading-5 text-slate-600">{card.detail}</div>
            <div className="mt-3">
              <Link href={appendReturnTo(card.href, returnTo)} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-100">
                {card.cta}
              </Link>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-4 grid gap-4 xl:grid-cols-[1.2fr_0.8fr]">
        <div className="rounded-xl border border-dashed bg-slate-50 p-4">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Next steps</div>
          <div className="mt-3 space-y-2 text-sm text-slate-700">
            {prompts.length ? prompts.map((prompt) => (
              <div key={prompt} className="rounded-lg bg-white px-3 py-2">{prompt}</div>
            )) : <div className="rounded-lg bg-white px-3 py-2 text-slate-500">No immediate issues are visible on the current board.</div>}
          </div>
        </div>

        <div className="rounded-xl border border-dashed bg-slate-50 p-4">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Work mix</div>
          <div className="mt-3 grid gap-2 text-sm text-slate-700">
            <div className="flex items-center justify-between rounded-lg bg-white px-3 py-2"><span>Available / draft</span><span className="font-semibold">{loads.filter((load) => load.status === "AVAILABLE" || load.status === "DRAFT").length}</span></div>
            <div className="flex items-center justify-between rounded-lg bg-white px-3 py-2"><span>Assigned / staging</span><span className="font-semibold">{loads.filter((load) => load.status === "ASSIGNED").length}</span></div>
            <div className="flex items-center justify-between rounded-lg bg-white px-3 py-2"><span>In transit</span><span className="font-semibold">{loads.filter((load) => load.status === "IN_TRANSIT").length}</span></div>
            <div className="flex items-center justify-between rounded-lg bg-white px-3 py-2"><span>Delivered / closeout</span><span className="font-semibold">{deliveredWaitingInvoice.length}</span></div>
            <div className="flex items-center justify-between rounded-lg bg-white px-3 py-2"><span>Invoiced / collections</span><span className="font-semibold">{loads.filter((load) => load.status === "INVOICED").length}</span></div>
          </div>
        </div>
      </div>
    </section>
  );
}
