import type { Load } 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 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 statusTone(tone: "READY" | "WATCH" | "ACTION") {
  switch (tone) {
    case "READY":
      return "border-emerald-200 bg-emerald-50 text-emerald-800";
    case "ACTION":
      return "border-red-200 bg-red-50 text-red-800";
    default:
      return "border-amber-200 bg-amber-50 text-amber-800";
  }
}

export function LoadExecutionReadinessPanel({ load }: { load: Load }) {
  const items = [
    load.truck?.id
      ? { key: "truck", label: "Truck assignment", tone: "READY" as const, body: `Truck ${load.truck.truckNumber} is attached to this load.` }
      : { key: "truck-missing", label: "Truck assignment", tone: "ACTION" as const, body: "No truck is assigned yet. Attach a truck before dispatching." },
    load.driver?.id
      ? { key: "driver", label: "Driver assignment", tone: "READY" as const, body: `${[load.driver.firstName, load.driver.lastName].filter(Boolean).join(" ") || "Assigned driver"} is attached, so team follow-up can stay tied to a real person.` }
      : { key: "driver-missing", label: "Driver assignment", tone: "ACTION" as const, body: "No driver is assigned yet. Assign a driver before pickup work continues." },
    load.broker?.id
      ? { key: "broker", label: "Broker visible", tone: "READY" as const, body: `${load.broker.name} is attached to the load, so invoice and broker coordination can continue without re-keying the record.` }
      : { key: "broker-missing", label: "Broker visible", tone: "WATCH" as const, body: "Broker details are incomplete. Billing and status updates may need manual lookup later." },
    load.rateConfirmationNumber
      ? { key: "ratecon", label: "Dispatch-ready paperwork", tone: "READY" as const, body: `Rate confirmation ${load.rateConfirmationNumber} is recorded.` }
      : { key: "ratecon-missing", label: "Dispatch-ready paperwork", tone: "WATCH" as const, body: "Rate confirmation number is missing. Add it when available." },
  ];

  return (
    <section className="rounded-2xl border bg-white p-5 shadow-sm">
      <div className="mb-4">
        <div className="text-sm font-semibold text-slate-900">Dispatch-ready details</div>
        <div className="text-xs text-slate-500">Details that keep assignment, billing, and problem-solving tied to this load.</div>
      </div>
      <div className="grid gap-3 md:grid-cols-2">
        {items.map((item) => (
          <div key={item.key} className={`rounded-xl border px-4 py-3 ${statusTone(item.tone)}`}>
            <div className="text-xs font-semibold uppercase tracking-wide">{item.label}</div>
            <div className="mt-2 text-sm leading-6">{item.body}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

export function LoadExceptionPromptsPanel({ load }: { load: Load }) {
  const prompts = [
    load.status === "IN_TRANSIT" && isPastDay(load.deliveryDate)
      ? { key: "late-delivery", tone: "ACTION" as const, label: "Late delivery", body: "Delivery date is now behind today while the load is still in transit. Get the driver update, broker update, and revised ETA before the load gets harder to manage." }
      : null,
    (load.status === "AVAILABLE" || load.status === "DRAFT") && (!load.driver?.id || !load.truck?.id)
      ? { key: "assignment-gap", tone: "ACTION" as const, label: "Assignment gap", body: "This load is not ready for dispatch. Attach both truck and driver before pickup work starts." }
      : null,
    load.status === "ASSIGNED" && sameDay(load.pickupDate)
      ? { key: "pickup-window", tone: "WATCH" as const, label: "Pickup window today", body: "Confirm driver contact, broker instructions, and any special requirements before dispatching the truck out." }
      : null,
    load.status === "IN_TRANSIT"
      ? { key: "check-call", tone: "WATCH" as const, label: "Check-call lane", body: "Keep the latest driver status and ETA current so the team do not have to infer movement from stale data." }
      : null,
    load.status === "DELIVERED"
      ? { key: "delivered-invoice", tone: "WATCH" as const, label: "Delivered / billing", body: "Delivery is complete. Move this record into invoice creation while details are fresh." }
      : null,
    load.status === "INVOICED" && Number(load.financialSummary?.outstandingAmount ?? 0) > 0
      ? { key: "payment-followup", tone: "WATCH" as const, label: "Payment follow-up", body: "Invoice is active but money is still outstanding. Keep this load visible for payment follow-up." }
      : null,
  ].filter(Boolean) as Array<{ key: string; tone: "READY" | "WATCH" | "ACTION"; label: string; body: string }>;

  return (
    <section className="rounded-2xl border bg-white p-5 shadow-sm">
      <div className="mb-4">
        <div className="text-sm font-semibold text-slate-900">Load issue prompts</div>
        <div className="text-xs text-slate-500">The most useful prompts for this load right now.</div>
      </div>
      {prompts.length ? (
        <div className="space-y-3">
          {prompts.map((prompt) => (
            <div key={prompt.key} className={`rounded-xl border px-4 py-3 ${statusTone(prompt.tone)}`}>
              <div className="text-xs font-semibold uppercase tracking-wide">{prompt.label}</div>
              <div className="mt-2 text-sm leading-6">{prompt.body}</div>
            </div>
          ))}
        </div>
      ) : (
        <div className="rounded-xl border border-dashed px-4 py-6 text-sm text-slate-500">No exception prompts are active on this load right now.</div>
      )}
    </section>
  );
}
