"use client";

import Link from "next/link";
import { useEffect, useMemo, useState, type ChangeEvent } from "react";
import { useSearchParams } from "next/navigation";
import { PageHeader } from "@/components/ui/page-header";
import { PlanFeatureGate } from "@/components/subscriptions/plan-feature-gate";
import { RouteDecisionFlow, RouteWorkspaceNavigation, RouteWorkspaceSummaryStrip } from "@/components/routes/route-workspace-navigation";
import { apiGet } from "@/lib/api";
import type { Driver, Load, Truck } from "@/types";

type ChatRole = "assistant" | "user";

type ChatMessage = {
  id: string;
  role: ChatRole;
  content: string;
};

type PlannerReadinessItem = {
  label: string;
  status: "ready" | "waiting";
  detail: string;
};

type RouteDatasetKey = "loads" | "trucks" | "drivers";

type LoadsResponse = { loads?: Load[]; items?: Load[]; data?: Load[] } | Load[];
type TrucksResponse = { trucks?: Truck[]; items?: Truck[]; data?: Truck[] } | Truck[];
type DriversResponse = { drivers?: Driver[]; items?: Driver[]; data?: Driver[] } | Driver[];

type RouteDatasetHealth = {
  key: RouteDatasetKey;
  status: "ready" | "warning";
  count: number;
  detail: string;
};

type RouteWeatherRisk = "low" | "moderate" | "high";

type RouteWeatherCheckpoint = {
  key: "pickup" | "corridor" | "delivery";
  label: string;
  locationLabel: string;
  temperatureF: number | null;
  precipitationProbability: number | null;
  windMph: number | null;
  summary: string;
  risk: RouteWeatherRisk;
  detail: string;
};

type RouteWeatherPlan = {
  provider: "OPEN_METEO" | "FOUNDATION_FALLBACK";
  mode: "live" | "fallback";
  summary: string;
  releaseGuidance: string;
  checkpoints: RouteWeatherCheckpoint[];
  fetchedAt: string;
};

type RouteAlternativeSummary = {
  rank: number;
  distanceMiles: number | null;
  durationHours: number | null;
  label: string;
};

type RouteMappingPlan = {
  provider: "OSRM" | "FOUNDATION_FALLBACK";
  mode: "live" | "fallback";
  summary: string;
  releaseGuidance: string;
  pickupLabel: string;
  deliveryLabel: string;
  distanceMiles: number | null;
  driveHours: number | null;
  etaNote: string;
  waypointCount: number;
  routeLine: Array<{ lat: number; lon: number }>;
  alternatives: RouteAlternativeSummary[];
  fetchedAt: string;
};

type RouteServiceCategory = "fuel" | "parking" | "repair" | "rest";

type RouteServiceStop = {
  id: string;
  name: string;
  category: RouteServiceCategory;
  locationLabel: string;
  distanceMiles: number | null;
  note: string;
};

type RouteServiceArea = {
  key: "pickup" | "corridor" | "delivery";
  label: string;
  locationLabel: string;
  summary: string;
  services: RouteServiceStop[];
};

type RouteServicePlan = {
  provider: "OVERPASS_OSM" | "FOUNDATION_FALLBACK";
  mode: "live" | "fallback";
  summary: string;
  releaseGuidance: string;
  areas: RouteServiceArea[];
  fetchedAt: string;
};

function asArray<T>(value: unknown): T[] {
  return Array.isArray(value) ? (value as T[]) : [];
}

function extractCollection<T>(value: unknown, keys: string[]): T[] {
  if (Array.isArray(value)) return value as T[];
  if (!value || typeof value !== "object") return [];

  for (const key of keys) {
    const candidate = (value as Record<string, unknown>)[key];
    if (Array.isArray(candidate)) return candidate as T[];
  }

  const objectValues = Object.values(value as Record<string, unknown>);
  const firstArray = objectValues.find(Array.isArray);
  return Array.isArray(firstArray) ? (firstArray as T[]) : [];
}

function coerceUniqueRecords<T extends { id: string }>(records: T[]): T[] {
  const seen = new Set<string>();
  const result: T[] = [];

  for (const record of records) {
    if (!record?.id || seen.has(record.id)) continue;
    seen.add(record.id);
    result.push(record);
  }

  return result;
}

function formatMoney(value?: string | null) {
  if (!value) return "-";
  const num = Number(value);
  if (Number.isNaN(num)) return value;
  return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 }).format(num);
}

function formatDriverName(driver?: Pick<Driver, "firstName" | "lastName"> | null) {
  const parts = [driver?.firstName, driver?.lastName].filter(Boolean);
  return parts.length ? parts.join(" ") : "Unassigned";
}

function formatTimestamp(value?: string | null) {
  if (!value) return "Not checked yet";
  const date = new Date(value);
  return Number.isNaN(date.getTime()) ? "Not checked yet" : date.toLocaleString();
}

function weatherRiskClasses(risk: RouteWeatherRisk) {
  if (risk === "high") return "bg-red-100 text-red-700";
  if (risk === "moderate") return "bg-amber-100 text-amber-700";
  return "bg-emerald-100 text-emerald-700";
}

function formatHours(value: number | null) {
  return typeof value === "number" ? `${value.toFixed(1)} hr` : "Manual review";
}

function formatMiles(value: number | null) {
  return typeof value === "number" ? `${value.toFixed(1)} mi` : "Manual review";
}

function serviceCategoryLabel(category: RouteServiceCategory) {
  if (category === "fuel") return "Fuel";
  if (category === "parking") return "Parking";
  if (category === "repair") return "Repair";
  return "Rest / services";
}

function serviceCategoryClasses(category: RouteServiceCategory) {
  if (category === "fuel") return "bg-emerald-100 text-emerald-700";
  if (category === "parking") return "bg-amber-100 text-amber-700";
  if (category === "repair") return "bg-rose-100 text-rose-700";
  return "bg-sky-100 text-sky-700";
}

function buildInitialMessage(load?: Load | null, truck?: Truck | null, driver?: Driver | null) {
  if (!load || !truck || !driver) {
    return "Select a load, a truck, and a driver first. Then CORI can help check the route, timing, weather, stops, and driver briefing.";
  }

  const lane = `${load.pickupLocation ?? "Unknown pickup"} to ${load.deliveryLocation ?? "Unknown delivery"}`;
  const miles = load.miles ? `${load.miles} mi` : "miles not entered yet";
  const delivery = load.deliveryDate ? `Target delivery: ${new Date(load.deliveryDate).toLocaleDateString()}.` : "Delivery timing still needs dispatcher review.";

  return `Routes CORI is ready. I am planning load ${load.referenceNumber ?? load.id.slice(0, 8)} on ${lane} using truck ${truck.truckNumber} and driver ${formatDriverName(driver)}. Base lane distance shows ${miles}. ${delivery} Ask for safest route, timing risk, weather, stops, or a driver briefing.`;
}

function buildRouteAdvice(load: Load, truck: Truck, driver: Driver, userPrompt: string) {
  const lower = userPrompt.toLowerCase();
  const lane = `${load.pickupLocation ?? "Unknown pickup"} to ${load.deliveryLocation ?? "Unknown delivery"}`;
  const milesNumber = Number(load.miles ?? 0);
  const mileageLine = milesNumber > 0 ? `Use ${milesNumber} posted load miles as the starting distance until the map check confirms the route.` : "This load does not have entered miles yet, so the dispatcher should confirm route distance before dispatching the driver.";
  const equipmentLine = `Truck ${truck.truckNumber} is recorded as ${truck.equipmentType}${truck.trailerType ? ` with ${truck.trailerType}` : ""}. Keep route restrictions and stop suitability aligned with that equipment.`;
  const driverLine = `${formatDriverName(driver)} should receive a route brief that confirms pickup, delivery, appointment timing, fuel/stop expectations, weather watch items, and any customer-specific notes.`;

  if (lower.includes("weather")) {
    return `Weather check is ready. Review pickup, road, and delivery weather, then confirm timing, storms, wind, and route buffer before sending the driver. ${equipmentLine}`;
  }

  if (lower.includes("stop") || lower.includes("fuel") || lower.includes("service")) {
    return `Stop planning is ready. Build the trip around hours, fuel range, safe truck parking, repairs, rest, and customer appointment times. ${mileageLine} ${driverLine}`;
  }

  if (lower.includes("brief") || lower.includes("driver")) {
    return `Driver briefing draft:\n- Load: ${load.referenceNumber ?? load.id.slice(0, 8)}\n- Lane: ${lane}\n- Truck: ${truck.truckNumber}\n- Driver: ${formatDriverName(driver)}\n- Route focus: safest practical route with time buffer around pickup and delivery\n- Dispatcher checks: customer notes, weather, fuel/stop plan, and paperwork\n- Do not send the driver until route, timing, and weather are checked.`;
  }

  if (lower.includes("time") || lower.includes("eta") || lower.includes("appointment")) {
    return `Timing check: ${mileageLine} Use that distance to estimate drive time, then layer on pickup appointment, rest requirements, fueling, traffic exposure, and delivery commitment. Check the timing before sending the driver.`;
  }

  return `Route review for ${lane}: start with the safest practical lane, confirm equipment fit, validate timing against pickup and delivery commitments, then add stop/fuel planning and weather review before briefing the driver. ${mileageLine} ${equipmentLine}`;
}

function buildHealthItem(key: RouteDatasetKey, count: number, context: { loading: boolean; error: string | null; selectedId: string; selectedFound: boolean }): RouteDatasetHealth {
  if (context.loading) {
    return {
      key,
      status: "warning",
      count,
      detail: "Loading these route choices now.",
    };
  }

  if (context.error) {
    return {
      key,
      status: "warning",
      count,
      detail: "These route choices did not finish loading.",
    };
  }

  if (count === 0) {
    return {
      key,
      status: "warning",
      count,
      detail: `No ${key} are available yet for route setup.`,
    };
  }

  if (context.selectedId && !context.selectedFound) {
    return {
      key,
      status: "warning",
      count,
      detail: `The selected ${key.slice(0, -1)} is no longer available, so the route setup was reset.`,
    };
  }

  return {
    key,
    status: "ready",
    count,
    detail: `${count} ${key} are ready for route setup.`,
  };
}

export default function RoutesPage() {
  const searchParams = useSearchParams();
  const [loads, setLoads] = useState<Load[]>([]);
  const [trucks, setTrucks] = useState<Truck[]>([]);
  const [drivers, setDrivers] = useState<Driver[]>([]);
  const [selectedLoadId, setSelectedLoadId] = useState("");
  const [selectedTruckId, setSelectedTruckId] = useState("");
  const [selectedDriverId, setSelectedDriverId] = useState("");
  const [prompt, setPrompt] = useState("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [weatherPlan, setWeatherPlan] = useState<RouteWeatherPlan | null>(null);
  const [weatherLoading, setWeatherLoading] = useState(false);
  const [weatherError, setWeatherError] = useState<string | null>(null);
  const [mappingPlan, setMappingPlan] = useState<RouteMappingPlan | null>(null);
  const [mappingLoading, setMappingLoading] = useState(false);
  const [mappingError, setMappingError] = useState<string | null>(null);
  const [servicePlan, setServicePlan] = useState<RouteServicePlan | null>(null);
  const [serviceLoading, setServiceLoading] = useState(false);
  const [serviceError, setServiceError] = useState<string | null>(null);

  useEffect(() => {
    let ignore = false;

    async function loadData() {
      setLoading(true);
      setError(null);
      try {
        const [loadsData, trucksData, driversData] = await Promise.all([
          apiGet<LoadsResponse>("/api/loads"),
          apiGet<TrucksResponse>("/api/trucks"),
          apiGet<DriversResponse>("/api/drivers"),
        ]);
        if (ignore) return;

        const nextLoads = coerceUniqueRecords(extractCollection<Load>(loadsData, ["loads", "items", "data"]));
        const nextTrucks = coerceUniqueRecords(extractCollection<Truck>(trucksData, ["trucks", "items", "data"]));
        const nextDrivers = coerceUniqueRecords(extractCollection<Driver>(driversData, ["drivers", "items", "data"]));

        setLoads(asArray(nextLoads));
        setTrucks(asArray(nextTrucks));
        setDrivers(asArray(nextDrivers));
      } catch (err) {
        if (ignore) return;
        setLoads([]);
        setTrucks([]);
        setDrivers([]);
        setError(err instanceof Error ? err.message : "Could not load route planning data.");
      } finally {
        if (!ignore) setLoading(false);
      }
    }

    loadData();
    return () => {
      ignore = true;
    };
  }, []);

  useEffect(() => {
    const loadId = searchParams.get("loadId") ?? "";
    const truckId = searchParams.get("truckId") ?? "";
    const driverId = searchParams.get("driverId") ?? "";
    if (loadId) setSelectedLoadId(loadId);
    if (truckId) setSelectedTruckId(truckId);
    if (driverId) setSelectedDriverId(driverId);
  }, [searchParams]);

  const selectedLoad = useMemo(() => loads.find((item: Load) => item.id === selectedLoadId) ?? null, [loads, selectedLoadId]);
  const selectedTruck = useMemo(() => trucks.find((item: Truck) => item.id === selectedTruckId) ?? null, [trucks, selectedTruckId]);
  const selectedDriver = useMemo(() => drivers.find((item: Driver) => item.id === selectedDriverId) ?? null, [drivers, selectedDriverId]);

  useEffect(() => {
    if (!selectedLoadId || selectedLoad) return;
    setSelectedLoadId("");
  }, [selectedLoadId, selectedLoad]);

  useEffect(() => {
    if (!selectedTruckId || selectedTruck) return;
    setSelectedTruckId("");
  }, [selectedTruckId, selectedTruck]);

  useEffect(() => {
    if (!selectedDriverId || selectedDriver) return;
    setSelectedDriverId("");
  }, [selectedDriverId, selectedDriver]);

  useEffect(() => {
    setMessages([
      {
        id: "initial",
        role: "assistant",
        content: buildInitialMessage(selectedLoad, selectedTruck, selectedDriver),
      },
    ]);
  }, [selectedLoad, selectedTruck, selectedDriver]);

  useEffect(() => {
    if (selectedLoad?.truck?.id && !selectedTruckId && trucks.some((truck: Truck) => truck.id === selectedLoad.truck?.id)) {
      setSelectedTruckId(selectedLoad.truck.id);
    }
    if (selectedLoad?.driver?.id && !selectedDriverId && drivers.some((driver: Driver) => driver.id === selectedLoad.driver?.id)) {
      setSelectedDriverId(selectedLoad.driver.id);
    }
  }, [drivers, selectedLoad, selectedTruckId, selectedDriverId, trucks]);

  useEffect(() => {
    let ignore = false;

    async function loadMapping() {
      if (!selectedLoad?.pickupLocation || !selectedLoad?.deliveryLocation) {
        setMappingPlan(null);
        setMappingError(null);
        setMappingLoading(false);
        return;
      }

      setMappingLoading(true);
      setMappingError(null);
      try {
        const nextPlan = await apiGet<RouteMappingPlan>(`/api/routes/mapping?pickup=${encodeURIComponent(selectedLoad.pickupLocation)}&delivery=${encodeURIComponent(selectedLoad.deliveryLocation)}`);
        if (ignore) return;
        setMappingPlan(nextPlan);
      } catch (err) {
        if (ignore) return;
        setMappingPlan(null);
        setMappingError(err instanceof Error ? err.message : "Could not load route check.");
      } finally {
        if (!ignore) setMappingLoading(false);
      }
    }

    loadMapping();
    return () => {
      ignore = true;
    };
  }, [selectedLoad?.pickupLocation, selectedLoad?.deliveryLocation]);

  useEffect(() => {
    let ignore = false;

    async function loadWeather() {
      if (!selectedLoad?.pickupLocation || !selectedLoad?.deliveryLocation) {
        setWeatherPlan(null);
        setWeatherError(null);
        setWeatherLoading(false);
        return;
      }

      setWeatherLoading(true);
      setWeatherError(null);
      try {
        const nextPlan = await apiGet<RouteWeatherPlan>(`/api/routes/weather?pickup=${encodeURIComponent(selectedLoad.pickupLocation)}&delivery=${encodeURIComponent(selectedLoad.deliveryLocation)}`);
        if (ignore) return;
        setWeatherPlan(nextPlan);
      } catch (err) {
        if (ignore) return;
        setWeatherPlan(null);
        setWeatherError(err instanceof Error ? err.message : "Could not load route weather review.");
      } finally {
        if (!ignore) setWeatherLoading(false);
      }
    }

    loadWeather();
    return () => {
      ignore = true;
    };
  }, [selectedLoad?.pickupLocation, selectedLoad?.deliveryLocation]);

  useEffect(() => {
    let ignore = false;

    async function loadServices() {
      if (!selectedLoad?.pickupLocation || !selectedLoad?.deliveryLocation) {
        setServicePlan(null);
        setServiceError(null);
        setServiceLoading(false);
        return;
      }

      setServiceLoading(true);
      setServiceError(null);
      try {
        const nextPlan = await apiGet<RouteServicePlan>(`/api/routes/services?pickup=${encodeURIComponent(selectedLoad.pickupLocation)}&delivery=${encodeURIComponent(selectedLoad.deliveryLocation)}`);
        if (ignore) return;
        setServicePlan(nextPlan);
      } catch (err) {
        if (ignore) return;
        setServicePlan(null);
        setServiceError(err instanceof Error ? err.message : "Could not load roadside services review.");
      } finally {
        if (!ignore) setServiceLoading(false);
      }
    }

    loadServices();
    return () => {
      ignore = true;
    };
  }, [selectedLoad?.pickupLocation, selectedLoad?.deliveryLocation]);

  const isReady = Boolean(selectedLoad && selectedTruck && selectedDriver);

  const readinessItems: PlannerReadinessItem[] = [
    {
      label: "Load selected",
      status: selectedLoad ? "ready" : "waiting",
      detail: selectedLoad
        ? `${selectedLoad.referenceNumber ?? selectedLoad.id.slice(0, 8)} · ${selectedLoad.pickupLocation ?? "Unknown pickup"} to ${selectedLoad.deliveryLocation ?? "Unknown delivery"}`
        : "Choose the load first so route planning starts from an actual job.",
    },
    {
      label: "Truck selected",
      status: selectedTruck ? "ready" : "waiting",
      detail: selectedTruck
        ? `${selectedTruck.truckNumber} · ${selectedTruck.equipmentType}`
        : "Choose the truck that will physically run the load.",
    },
    {
      label: "Driver selected",
      status: selectedDriver ? "ready" : "waiting",
      detail: selectedDriver
        ? `${formatDriverName(selectedDriver)}${selectedDriver.phone ? ` · ${selectedDriver.phone}` : ""}`
        : "Choose the driver before asking CORI for route advice.",
    },
  ];

  const dataHealthItems: RouteDatasetHealth[] = [
    buildHealthItem("loads", loads.length, { loading, error, selectedId: selectedLoadId, selectedFound: Boolean(selectedLoad) }),
    buildHealthItem("trucks", trucks.length, { loading, error, selectedId: selectedTruckId, selectedFound: Boolean(selectedTruck) }),
    buildHealthItem("drivers", drivers.length, { loading, error, selectedId: selectedDriverId, selectedFound: Boolean(selectedDriver) }),
  ];

  const plannerPrompts = [
    "Give me the safest first route review.",
    "What timing risks should I check before dispatching?",
    "What weather checkpoints should I review?",
    "Draft the driver briefing.",
  ];

  const summaryItems = [
    {
      label: "Ready loads",
      value: loads.length,
      helper: loading ? "Loading route load options now." : "Loads available for route planning.",
      tone: "blue" as const,
    },
    {
      label: "Available trucks",
      value: trucks.length,
      helper: loading ? "Loading truck options now." : "Trucks available for route planning.",
      tone: "slate" as const,
    },
    {
      label: "Available drivers",
      value: drivers.length,
      helper: loading ? "Loading driver options now." : "Drivers available for route planning.",
      tone: "slate" as const,
    },
    {
      label: "Current route setup",
      value: isReady ? "Ready" : "Waiting",
      helper: isReady ? "Load, truck, and driver are selected for route review." : "Choose the full load + truck + driver combination first.",
      tone: isReady ? ("emerald" as const) : ("amber" as const),
    },
  ];

  const routeDecisionItems = [
    {
      label: "Route setup",
      value: [selectedLoad, selectedTruck, selectedDriver].filter(Boolean).length,
      helper: isReady ? "Load, truck, and driver are selected." : "Route help starts after load, truck, and driver are selected.",
      tone: isReady ? ("emerald" as const) : ("amber" as const),
    },
    {
      label: "Lane check",
      value: mappingPlan ? 3 : selectedLoad ? 2 : 0,
      helper: mappingPlan ? "Route miles, drive hours, and alternates are ready." : selectedLoad ? "Lane check is loading." : "Select a load to begin the lane check.",
      tone: mappingPlan ? ("blue" as const) : ("slate" as const),
    },
    {
      label: "Weather and stops",
      value: Number(Boolean(weatherPlan)) + Number(Boolean(servicePlan)),
      helper: weatherPlan || servicePlan ? "Weather and stop checks are ready." : "Weather and stop checks appear after you select the lane.",
      tone: weatherPlan || servicePlan ? ("blue" as const) : ("slate" as const),
    },
    {
      label: "Ready to brief driver",
      value: Number(Boolean(mappingPlan)) + Number(Boolean(weatherPlan)) + Number(Boolean(servicePlan)),
      helper: isReady ? "Check lane, weather, and stops before briefing the driver." : "The driver briefing is not ready until setup is complete.",
      tone: isReady && mappingPlan ? ("emerald" as const) : ("amber" as const),
    },
  ];

  function sendPrompt(nextPrompt?: string) {
    const outgoing = (nextPrompt ?? prompt).trim();
    if (!outgoing || !selectedLoad || !selectedTruck || !selectedDriver) return;

    const userMessage: ChatMessage = {
      id: `user-${Date.now()}`,
      role: "user",
      content: outgoing,
    };

    const assistantMessage: ChatMessage = {
      id: `assistant-${Date.now()}`,
      role: "assistant",
      content: buildRouteAdvice(selectedLoad, selectedTruck, selectedDriver, outgoing),
    };

    setMessages((current: ChatMessage[]) => [...current, userMessage, assistantMessage]);
    setPrompt("");
  }

  const pageAction = (
    <div className="flex flex-wrap gap-2">
      <Link href="/dispatch" className="rounded-xl border bg-white px-4 py-2 text-sm font-medium">Back to Dispatch</Link>
      <Link href="/cori" className="rounded-xl border bg-white px-4 py-2 text-sm font-medium">Open Ask CORI</Link>
    </div>
  );

  return (
    <PlanFeatureGate feature="routePlanning">
      <div className="space-y-6">
      <PageHeader
        title="Routes"
        subtitle="Select the load, truck, and driver. Then ask CORI for the safest route and driver briefing."
        action={pageAction}
      />

      <RouteWorkspaceNavigation currentHref="/routes" />

      <RouteWorkspaceSummaryStrip items={summaryItems} />

      <RouteDecisionFlow items={routeDecisionItems} />


      <section className="rounded-3xl border bg-white p-5 shadow-sm">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-gray-900">Pick these first</div>
            <p className="mt-1 max-w-3xl text-sm text-gray-500">CORI needs the load, truck, and driver before giving route advice.</p>
          </div>
          <div className={`rounded-full px-3 py-1 text-xs font-semibold ${isReady ? "bg-emerald-100 text-emerald-700" : "bg-amber-100 text-amber-700"}`}>
            {isReady ? "Ready for route review" : "Waiting on required selections"}
          </div>
        </div>

        <div className="mt-5 grid gap-4 xl:grid-cols-[1.2fr_0.8fr]">
          <div className="grid gap-4 md:grid-cols-3">
            <label className="rounded-2xl border bg-gray-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">Load</div>
              <select value={selectedLoadId} onChange={(event: ChangeEvent<HTMLSelectElement>) => setSelectedLoadId(event.target.value)} className="mt-3 w-full rounded-xl border bg-white px-3 py-2 text-sm">
                <option value="">Select load</option>
                {loads.map((load: Load) => (
                  <option key={load.id} value={load.id}>{load.referenceNumber ?? load.id.slice(0, 8)} · {load.pickupLocation ?? "Unknown pickup"} → {load.deliveryLocation ?? "Unknown delivery"}</option>
                ))}
              </select>
              <div className="mt-3 text-xs text-gray-500">{selectedLoad ? `${selectedLoad.status} · ${formatMoney(selectedLoad.financialSummary?.grossRevenue ?? selectedLoad.invoiceAmount)}` : "Pick the shipment that needs planning."}</div>
            </label>

            <label className="rounded-2xl border bg-gray-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">Truck</div>
              <select value={selectedTruckId} onChange={(event: ChangeEvent<HTMLSelectElement>) => setSelectedTruckId(event.target.value)} className="mt-3 w-full rounded-xl border bg-white px-3 py-2 text-sm">
                <option value="">Select truck</option>
                {trucks.map((truck: Truck) => (
                  <option key={truck.id} value={truck.id}>{truck.truckNumber} · {truck.equipmentType}</option>
                ))}
              </select>
              <div className="mt-3 text-xs text-gray-500">{selectedTruck ? `${selectedTruck.make ?? "Truck"} ${selectedTruck.model ?? ""} ${selectedTruck.trailerType ? `· ${selectedTruck.trailerType}` : ""}`.trim() : "Pick the unit that will run the route."}</div>
            </label>

            <label className="rounded-2xl border bg-gray-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">Driver</div>
              <select value={selectedDriverId} onChange={(event: ChangeEvent<HTMLSelectElement>) => setSelectedDriverId(event.target.value)} className="mt-3 w-full rounded-xl border bg-white px-3 py-2 text-sm">
                <option value="">Select driver</option>
                {drivers.map((driver: Driver) => (
                  <option key={driver.id} value={driver.id}>{formatDriverName(driver)}{driver.truck?.truckNumber ? ` · Truck ${driver.truck.truckNumber}` : ""}</option>
                ))}
              </select>
              <div className="mt-3 text-xs text-gray-500">{selectedDriver ? `${selectedDriver.phone ?? "No phone on file"}${selectedDriver.payType ? ` · ${selectedDriver.payType}` : ""}` : "Pick the person who will execute the trip."}</div>
            </label>
          </div>

          <div className="rounded-2xl border bg-slate-950 p-4 text-white">
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-300">Ready check</div>
            <div className="mt-4 space-y-3">
              {readinessItems.map((item: PlannerReadinessItem) => (
                <div key={item.label} className="rounded-2xl border border-white/10 bg-white/5 p-3">
                  <div className="flex items-center justify-between gap-3">
                    <div className="text-sm font-medium">{item.label}</div>
                    <span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${item.status === "ready" ? "bg-emerald-400/15 text-emerald-200" : "bg-amber-400/15 text-amber-200"}`}>
                      {item.status === "ready" ? "Ready" : "Waiting"}
                    </span>
                  </div>
                  <div className="mt-2 text-xs text-slate-300">{item.detail}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>


      <div className="grid gap-6 xl:grid-cols-[1.25fr_0.75fr]">
        <section className="rounded-3xl border bg-white p-5 shadow-sm">
          <div className="flex flex-col gap-3 border-b pb-4 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <div className="text-sm font-semibold text-gray-900">Routes CORI</div>
              <p className="mt-1 text-sm text-gray-500">Ask route questions and prepare a simple driver briefing.</p>
            </div>
            <div className={`rounded-full px-3 py-1 text-xs font-semibold ${isReady ? "bg-emerald-100 text-emerald-700" : "bg-gray-100 text-gray-600"}`}>
              {isReady ? "CORI ready" : "Pick load, truck, driver"}
            </div>
          </div>

          <div className="mt-4 space-y-3">
            {messages.map((message: ChatMessage) => (
              <div key={message.id} className={`max-w-4xl rounded-2xl px-4 py-3 text-sm ${message.role === "assistant" ? "bg-gray-100 text-gray-800" : "ml-auto bg-slate-950 text-white"}`}>
                <div className="mb-1 text-[11px] font-semibold uppercase tracking-[0.18em] opacity-70">{message.role === "assistant" ? "Routes CORI" : "Dispatcher"}</div>
                <div className="whitespace-pre-line">{message.content}</div>
              </div>
            ))}
          </div>

          <div className="mt-5 rounded-2xl border bg-gray-50 p-4">
            <div className="flex flex-wrap gap-2">
              {plannerPrompts.map((item: string) => (
                <button key={item} type="button" disabled={!isReady} onClick={() => sendPrompt(item)} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 disabled:cursor-not-allowed disabled:opacity-50">
                  {item}
                </button>
              ))}
            </div>
            <div className="mt-3 flex flex-col gap-3 sm:flex-row">
              <input value={prompt} onChange={(event: ChangeEvent<HTMLInputElement>) => setPrompt(event.target.value)} disabled={!isReady} placeholder={isReady ? "Ask about route, timing, weather, stops, or driver briefing" : "Select load + truck + driver first"} className="min-w-0 flex-1 rounded-xl border bg-white px-3 py-2 text-sm disabled:bg-gray-100" />
              <button type="button" onClick={() => sendPrompt()} disabled={!isReady || !prompt.trim()} className="rounded-xl bg-black px-4 py-2 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50">Send</button>
            </div>
          </div>
        </section>

        <div className="space-y-6">
          <section className="rounded-3xl border bg-white p-5 shadow-sm">
            <div className="text-sm font-semibold text-gray-900">Route checks</div>
            <div className="mt-4 space-y-3">
              <div className="rounded-2xl border bg-gray-50 p-4">
                <div className="flex items-center justify-between gap-3">
                  <div className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">Mapping</div>
                  <span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${mappingPlan?.mode === "live" ? "bg-indigo-100 text-indigo-700" : "bg-gray-200 text-gray-700"}`}>
                    {mappingPlan?.mode === "live" ? "Map check ready" : "Manual check"}
                  </span>
                </div>
                <div className="mt-2 text-sm text-gray-700">
                  {selectedLoad ? "This shows route miles, drive hours, and possible alternate routes for the selected pickup and delivery." : "Select a load first so route mapping can begin from the actual lane."}
                </div>

                {mappingLoading ? <div className="mt-3 rounded-2xl border bg-white px-3 py-2 text-xs text-gray-500">Loading route check…</div> : null}
                {mappingError ? <div className="mt-3 rounded-2xl border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700">{mappingError}</div> : null}

                {mappingPlan ? (
                  <div className="mt-4 space-y-3">
                    <div className="rounded-2xl border bg-white p-3">
                      <div className="flex items-center justify-between gap-3">
                        <div className="text-sm font-medium text-gray-900">{mappingPlan.summary}</div>
                        <div className="text-[11px] text-gray-500">Checked {formatTimestamp(mappingPlan.fetchedAt)}</div>
                      </div>
                      <div className="mt-3 grid grid-cols-2 gap-2 text-xs text-gray-600">
                        <div className="rounded-xl bg-gray-50 px-2 py-2"><span className="block text-[10px] uppercase tracking-[0.16em] text-gray-400">Miles</span>{formatMiles(mappingPlan.distanceMiles)}</div>
                        <div className="rounded-xl bg-gray-50 px-2 py-2"><span className="block text-[10px] uppercase tracking-[0.16em] text-gray-400">Drive hours</span>{formatHours(mappingPlan.driveHours)}</div>
                      </div>
                      <div className="mt-3 text-xs text-gray-600">{mappingPlan.etaNote}</div>
                      <div className="mt-2 text-[11px] text-gray-500">Check: {mappingPlan.provider === "OSRM" ? "route map" : "manual route list"}</div>
                    </div>
                    <div className="rounded-2xl border bg-white p-3">
                      <div className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">Route path</div>
                      <div className="mt-2 text-sm text-gray-700">{mappingPlan.pickupLabel} → {mappingPlan.deliveryLabel}</div>
                      <div className="mt-1 text-xs text-gray-500">{mappingPlan.routeLine.length > 0 ? `Route path is loaded with ${mappingPlan.waypointCount} waypoint${mappingPlan.waypointCount === 1 ? "" : "s"}.` : "Route path is not available, so confirm the lane manually."}</div>
                    </div>
                    {mappingPlan.alternatives.length ? (
                      <div className="rounded-2xl border bg-white p-3">
                        <div className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">Alternate lane comparison</div>
                        <div className="mt-3 space-y-2">
                          {mappingPlan.alternatives.map((alternative: RouteAlternativeSummary) => (
                            <div key={alternative.rank} className="rounded-xl bg-gray-50 px-3 py-2 text-xs text-gray-700">
                              <div className="font-medium text-gray-900">{alternative.label}</div>
                              <div className="mt-1">{formatMiles(alternative.distanceMiles)} · {formatHours(alternative.durationHours)}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                    ) : null}
                    <div className="rounded-2xl border bg-indigo-50 p-3 text-xs text-indigo-800">{mappingPlan.releaseGuidance}</div>
                  </div>
                ) : null}
              </div>
              <div className="rounded-2xl border bg-gray-50 p-4">
                <div className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">Timing</div>
                <div className="mt-2 text-sm text-gray-700">{mappingPlan ? mappingPlan.etaNote : "Choose a load to see drive time, stop windows, ETA checks, and appointment timing."}</div>
                <div className="mt-3 grid grid-cols-2 gap-2 text-xs text-gray-600">
                  <div className="rounded-xl bg-white px-2 py-2"><span className="block text-[10px] uppercase tracking-[0.16em] text-gray-400">Primary lane</span>{mappingPlan ? formatMiles(mappingPlan.distanceMiles) : "Waiting on lane"}</div>
                  <div className="rounded-xl bg-white px-2 py-2"><span className="block text-[10px] uppercase tracking-[0.16em] text-gray-400">Base ETA</span>{mappingPlan ? formatHours(mappingPlan.driveHours) : "Waiting on lane"}</div>
                </div>
                <div className="mt-3 text-xs text-gray-500">{mappingPlan ? "Dispatcher should still add customer appointments, traffic exposure, fuel/stop structure, and legal breaks before sending the driver." : "Route timing will appear here after the lane check loads."}</div>
              </div>
              <div className="rounded-2xl border bg-gray-50 p-4">
                <div className="flex items-center justify-between gap-3">
                  <div className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">Weather</div>
                  <span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${weatherPlan?.mode === "live" ? "bg-sky-100 text-sky-700" : "bg-gray-200 text-gray-700"}`}>
                    {weatherPlan?.mode === "live" ? "Weather check ready" : "Manual check"}
                  </span>
                </div>
                <div className="mt-2 text-sm text-gray-700">
                  {selectedLoad ? "This checks pickup, road, and delivery weather for the selected lane." : "Select a load first so route weather review can begin from the actual lane."}
                </div>

                {weatherLoading ? <div className="mt-3 rounded-2xl border bg-white px-3 py-2 text-xs text-gray-500">Loading weather check…</div> : null}
                {weatherError ? <div className="mt-3 rounded-2xl border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700">{weatherError}</div> : null}

                {weatherPlan ? (
                  <div className="mt-4 space-y-3">
                    <div className="rounded-2xl border bg-white p-3">
                      <div className="flex items-center justify-between gap-3">
                        <div className="text-sm font-medium text-gray-900">{weatherPlan.summary}</div>
                        <div className="text-[11px] text-gray-500">Checked {formatTimestamp(weatherPlan.fetchedAt)}</div>
                      </div>
                      <div className="mt-2 text-xs text-gray-600">{weatherPlan.releaseGuidance}</div>
                      <div className="mt-2 text-[11px] text-gray-500">Check: {weatherPlan.provider === "OPEN_METEO" ? "weather" : "manual weather list"}</div>
                    </div>
                    {weatherPlan.checkpoints.map((checkpoint: RouteWeatherCheckpoint) => (
                      <div key={checkpoint.key} className="rounded-2xl border bg-white p-3">
                        <div className="flex items-start justify-between gap-3">
                          <div>
                            <div className="text-sm font-medium text-gray-900">{checkpoint.label}</div>
                            <div className="mt-1 text-xs text-gray-500">{checkpoint.locationLabel}</div>
                          </div>
                          <span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${weatherRiskClasses(checkpoint.risk)}`}>
                            {checkpoint.risk === "high" ? "High risk" : checkpoint.risk === "moderate" ? "Moderate risk" : "Low risk"}
                          </span>
                        </div>
                        <div className="mt-3 grid grid-cols-3 gap-2 text-xs text-gray-600">
                          <div className="rounded-xl bg-gray-50 px-2 py-2"><span className="block text-[10px] uppercase tracking-[0.16em] text-gray-400">Temp</span>{checkpoint.temperatureF !== null ? `${checkpoint.temperatureF}°F` : "Manual check"}</div>
                          <div className="rounded-xl bg-gray-50 px-2 py-2"><span className="block text-[10px] uppercase tracking-[0.16em] text-gray-400">Precip</span>{checkpoint.precipitationProbability !== null ? `${checkpoint.precipitationProbability}%` : "Manual check"}</div>
                          <div className="rounded-xl bg-gray-50 px-2 py-2"><span className="block text-[10px] uppercase tracking-[0.16em] text-gray-400">Wind</span>{checkpoint.windMph !== null ? `${checkpoint.windMph} mph` : "Manual check"}</div>
                        </div>
                        <div className="mt-3 text-sm text-gray-700">{checkpoint.summary}</div>
                        <div className="mt-1 text-xs text-gray-500">{checkpoint.detail}</div>
                      </div>
                    ))}
                    <div className="rounded-2xl border bg-sky-50 p-3 text-xs text-sky-800">Recheck weather right before sending the driver.</div>
                  </div>
                ) : null}
              </div>
              <div className="rounded-2xl border bg-gray-50 p-4">
                <div className="flex items-center justify-between gap-3">
                  <div className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">Stops & services</div>
                  <span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${servicePlan?.mode === "live" ? "bg-teal-100 text-teal-700" : "bg-gray-200 text-gray-700"}`}>
                    {servicePlan?.mode === "live" ? "Stop check ready" : "Manual check"}
                  </span>
                </div>
                <div className="mt-2 text-sm text-gray-700">{selectedLoad ? "This helps check fuel, parking, repair, and rest stops around the pickup, route, and delivery." : "Select a load first so roadside support planning can begin from the actual lane."}</div>

                {serviceLoading ? <div className="mt-3 rounded-2xl border bg-white px-3 py-2 text-xs text-gray-500">Loading stop options…</div> : null}
                {serviceError ? <div className="mt-3 rounded-2xl border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700">{serviceError}</div> : null}

                {servicePlan ? (
                  <div className="mt-4 space-y-3">
                    <div className="rounded-2xl border bg-white p-3">
                      <div className="flex items-center justify-between gap-3">
                        <div className="text-sm font-medium text-gray-900">{servicePlan.summary}</div>
                        <div className="text-[11px] text-gray-500">Checked {formatTimestamp(servicePlan.fetchedAt)}</div>
                      </div>
                      <div className="mt-2 text-xs text-gray-600">{servicePlan.releaseGuidance}</div>
                      <div className="mt-2 text-[11px] text-gray-500">Check: {servicePlan.provider === "OVERPASS_OSM" ? "roadside stops" : "manual stop list"}</div>
                    </div>

                    {servicePlan.areas.map((area: RouteServiceArea) => (
                      <div key={area.key} className="rounded-2xl border bg-white p-3">
                        <div className="flex items-start justify-between gap-3">
                          <div>
                            <div className="text-sm font-medium text-gray-900">{area.label}</div>
                            <div className="mt-1 text-xs text-gray-500">{area.locationLabel}</div>
                          </div>
                          <div className="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-semibold text-slate-700">{area.services.length} stop{area.services.length === 1 ? "" : "s"}</div>
                        </div>
                        <div className="mt-2 text-xs text-gray-600">{area.summary}</div>
                        {area.services.length ? (
                          <div className="mt-3 space-y-2">
                            {area.services.map((service: RouteServiceStop) => (
                              <div key={service.id} className="rounded-xl bg-gray-50 px-3 py-3 text-xs text-gray-700">
                                <div className="flex flex-wrap items-center justify-between gap-2">
                                  <div className="font-medium text-gray-900">{service.name}</div>
                                  <div className="flex flex-wrap items-center gap-2">
                                    <span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${serviceCategoryClasses(service.category)}`}>{serviceCategoryLabel(service.category)}</span>
                                    <span className="rounded-full bg-white px-2 py-0.5 text-[11px] font-semibold text-slate-700">{formatMiles(service.distanceMiles)}</span>
                                  </div>
                                </div>
                                <div className="mt-1 text-[11px] text-gray-500">{service.locationLabel}</div>
                                <div className="mt-2 text-xs text-gray-600">{service.note}</div>
                              </div>
                            ))}
                          </div>
                        ) : (
                          <div className="mt-3 rounded-xl bg-gray-50 px-3 py-2 text-xs text-gray-500">No stops were returned for this area. Confirm fuel, parking, or repair options manually before sending the driver.</div>
                        )}
                      </div>
                    ))}
                    <div className="rounded-2xl border bg-teal-50 p-3 text-xs text-teal-800">Use these stops as starting options only. Confirm truck access, hours, parking, and customer timing before sending the driver.</div>
                  </div>
                ) : null}
              </div>
            </div>
          </section>

          <section className="rounded-3xl border bg-white p-5 shadow-sm">
            <div className="text-sm font-semibold text-gray-900">Dispatcher summary</div>
            <div className="mt-4 space-y-3 text-sm text-gray-700">
              <div className="rounded-2xl border bg-gray-50 p-4">
                <div className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">Selected lane</div>
                <div className="mt-2 font-medium text-gray-900">{selectedLoad ? `${selectedLoad.pickupLocation ?? "Unknown pickup"} → ${selectedLoad.deliveryLocation ?? "Unknown delivery"}` : "No load selected yet"}</div>
                <div className="mt-1 text-xs text-gray-500">{selectedLoad ? `Load ref ${selectedLoad.referenceNumber ?? selectedLoad.id.slice(0, 8)} · Status ${selectedLoad.status}` : "The route page will summarize the lane after setup is complete."}</div>
              </div>
              <div className="rounded-2xl border bg-gray-50 p-4">
                <div className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">Assigned unit</div>
                <div className="mt-2 font-medium text-gray-900">{selectedTruck ? `${selectedTruck.truckNumber} · ${selectedTruck.equipmentType}` : "No truck selected yet"}</div>
                <div className="mt-1 text-xs text-gray-500">{selectedDriver ? `Driver ${formatDriverName(selectedDriver)}` : "Driver still needs to be selected."}</div>
              </div>
              <div className="rounded-2xl border bg-gray-50 p-4">
                <div className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">Driver briefing</div>
                <div className="mt-2 text-sm text-gray-700">{weatherPlan ? weatherPlan.releaseGuidance : mappingPlan ? mappingPlan.releaseGuidance : servicePlan ? servicePlan.releaseGuidance : "The final driver briefing will appear here after route checks are ready."}</div>
                <div className="mt-2 text-xs text-gray-500">{weatherPlan ? `Weather: ${weatherPlan.mode === "live" ? "check ready" : "manual check"}` : mappingPlan ? `Map: ${mappingPlan.mode === "live" ? "check ready" : "manual check"}` : servicePlan ? `Stops: ${servicePlan.mode === "live" ? "check ready" : "manual check"}` : "Route guidance will appear here after the lane check loads."}</div>
              </div>
            </div>
          </section>
        </div>
      </div>

      {loading ? <div className="rounded-2xl border bg-white p-4 text-sm text-gray-500 shadow-sm">Loading route records…</div> : null}
      {error ? <div className="rounded-2xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 shadow-sm">{error}</div> : null}
      </div>
    </PlanFeatureGate>
  );
}
