import type { Load } from "@/types";

function formatDateTime(value?: string | null) {
  if (!value) return "-";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.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 hoursSince(value?: string | null) {
  if (!value) return null;
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return null;
  return Math.floor((Date.now() - d.getTime()) / (1000 * 60 * 60));
}

function toneClasses(tone: "ready" | "watch" | "action") {
  if (tone === "ready") return "border-emerald-200 bg-emerald-50 text-emerald-800";
  if (tone === "action") return "border-amber-200 bg-amber-50 text-amber-800";
  return "border-slate-200 bg-slate-50 text-slate-800";
}

function latestOperationalUpdate(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;
}

export function CheckCallCaptureVisibilityPanel({ load }: { load: Load }) {
  const latestUpdate = latestOperationalUpdate(load);
  const staleHours = hoursSince(latestUpdate?.changedAt);
  const inTransit = load.status === "IN_TRANSIT";
  const needsAssignment = (load.status === "AVAILABLE" || load.status === "DRAFT") && (!load.driver?.id || !load.truck?.id);
  const deliveryLate = inTransit && isPastDay(load.deliveryDate);
  const deliveryToday = inTransit && sameDay(load.deliveryDate);
  const updateTone: "ready" | "watch" | "action" = deliveryLate
    ? "action"
    : inTransit && (staleHours == null || staleHours >= 12)
      ? "watch"
      : inTransit
        ? "ready"
        : "watch";

  const recommendedCapture = needsAssignment
    ? "Confirm the truck, driver, and broker before pickup starts."
    : deliveryLate
      ? "Capture revised ETA, broker notification, and next driver update now."
      : deliveryToday
        ? "Confirm final ETA, receiver timing, and delivery completion path."
        : inTransit
          ? "Keep the latest location, ETA, and broker-facing update visible on this load."
          : load.status === "DELIVERED"
            ? "Delivery work is complete. Capture billing details while POD details are fresh."
            : "No active check-call capture lane is required right now.";

  return (
    <section className="rounded-2xl border bg-white p-5 shadow-sm">
      <div>
        <div className="text-sm font-semibold text-slate-900">Check call notes</div>
        <div className="text-xs text-slate-500">Operational update awareness for the current load, using assignment state, status history, and milestone timing already on the record.</div>
      </div>

      <div className="mt-4 grid gap-3 md:grid-cols-3">
        <div className={`rounded-xl border px-4 py-3 ${toneClasses(updateTone)}`}>
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em]">Latest operational update</div>
          <div className="mt-2 text-sm font-semibold">{latestUpdate ? `${latestUpdate.toStatus.replaceAll("_", " ")} · ${formatDateTime(latestUpdate.changedAt)}` : "No status-history updates yet"}</div>
          <div className="mt-1 text-xs">{latestUpdate?.note?.trim() || "No note is attached to the latest update."}</div>
        </div>
        <div className="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-slate-800">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em]">Recommended capture</div>
          <div className="mt-2 text-sm font-semibold">{recommendedCapture}</div>
          <div className="mt-1 text-xs">{inTransit ? "This keeps dispatch, billing, and exception handling working from the same load record." : "This lane becomes more important once the load enters active movement."}</div>
        </div>
        <div className="rounded-xl border border-slate-200 bg-white px-4 py-3 text-slate-800">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em]">Contact path</div>
          <div className="mt-2 space-y-1 text-sm">
            <div>Driver: <span className="font-medium">{[load.driver?.firstName, load.driver?.lastName].filter(Boolean).join(" ") || "Missing driver assignment"}</span></div>
            <div>Truck: <span className="font-medium">{load.truck?.truckNumber || "Missing truck assignment"}</span></div>
            <div>Broker: <span className="font-medium">{load.broker?.name || "Missing broker"}</span></div>
          </div>
        </div>
      </div>
    </section>
  );
}

const milestoneOrder = [
  { key: "DRAFT", label: "Draft", guidance: "Finish core load details and make the load dispatchable." },
  { key: "AVAILABLE", label: "Available", guidance: "Confirm the load is ready to assign without missing route or broker basics." },
  { key: "ASSIGNED", label: "Assigned", guidance: "Lock truck and driver ownership, then confirm pickup timing and contact path." },
  { key: "IN_TRANSIT", label: "In Transit", guidance: "Keep check calls, ETA movement, and exception follow-up current." },
  { key: "DELIVERED", label: "Delivered", guidance: "Confirm POD path and move quickly into billing." },
  { key: "INVOICED", label: "Invoiced", guidance: "Follow collections while the delivery and invoice timeline are still fresh." },
  { key: "PAID_FULL", label: "Paid", guidance: "This load is paid and ready to close." },
] as const;

function milestoneState(currentStatus: string, stepKey: string) {
  const currentIndex = milestoneOrder.findIndex((step) => step.key === currentStatus);
  const stepIndex = milestoneOrder.findIndex((step) => step.key === stepKey);
  if (currentIndex === -1 || stepIndex === -1) return "upcoming" as const;
  if (stepIndex < currentIndex) return "complete" as const;
  if (stepIndex === currentIndex) return "current" as const;
  return "upcoming" as const;
}

export function PickupToDeliveryMilestoneGuidancePanel({ load }: { load: Load }) {
  const timingNote = load.status === "IN_TRANSIT" && isPastDay(load.deliveryDate)
    ? "Delivery date is behind today. Work this load as an exception until ETA and receiver details are clear."
    : (load.status === "AVAILABLE" || load.status === "ASSIGNED") && sameDay(load.pickupDate)
      ? "Pickup is today. Keep assignment and dispatch communication tight."
      : load.status === "IN_TRANSIT" && sameDay(load.deliveryDate)
        ? "Delivery is today. Keep final ETA and receiver details visible."
        : "Use the current milestone to guide what dispatch should tighten next on this load.";

  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">Pickup-to-delivery milestone guidance</div>
          <div className="text-xs text-slate-500">A simple path from setup through payment, based on the current load status.</div>
        </div>
        <div className="rounded-full border bg-slate-50 px-3 py-1 text-xs font-semibold text-slate-700">
          Current status: {load.status.replaceAll("_", " ")}
        </div>
      </div>

      <div className="mt-3 rounded-xl border border-dashed bg-slate-50 px-4 py-3 text-sm text-slate-700">{timingNote}</div>

      <div className="mt-4 space-y-3">
        {milestoneOrder.map((step) => {
          const state = milestoneState(load.status, step.key);
          const classes = state === "complete"
            ? "border-emerald-200 bg-emerald-50"
            : state === "current"
              ? "border-slate-900 bg-slate-50"
              : "border-slate-200 bg-white";
          const marker = state === "complete" ? "Complete" : state === "current" ? "Current" : "Upcoming";
          return (
            <div key={step.key} className={`rounded-xl border px-4 py-3 ${classes}`}>
              <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">{marker}</div>
              </div>
              <div className="mt-1 text-sm text-slate-600">{step.guidance}</div>
            </div>
          );
        })}
      </div>
    </section>
  );
}
