"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { apiGet } from "@/lib/api";
import type { Load, Truck } from "@/types";

type LoadsResponse = { loads: Load[] };
type TrucksResponse = { trucks: Truck[] };

type FitSuggestion = {
  key: string;
  headline: string;
  truckLine: string;
  loadLine: string;
  supportLine: string;
  loadId: string;
  question: string;
};

function loadLabel(load: Load) {
  return load.referenceNumber ?? load.rateConfirmationNumber ?? load.id.slice(0, 8).toUpperCase();
}

function routeLabel(load: Pick<Load, "pickupLocation" | "deliveryLocation">) {
  if (load.pickupLocation && load.deliveryLocation) return `${load.pickupLocation} to ${load.deliveryLocation}`;
  return load.pickupLocation || load.deliveryLocation || "Route not set";
}

function truckDriverLabel(truck: Truck) {
  const driver = truck.drivers?.[0];
  const driverName = [driver?.firstName, driver?.lastName].filter(Boolean).join(" ");
  return driverName ? `Truck ${truck.truckNumber} · ${driverName}` : `Truck ${truck.truckNumber}`;
}

function normalizeEquipment(value?: string | null) {
  return String(value ?? "").trim().toLowerCase();
}

function isTruckOpen(truck: Truck) {
  const status = String(truck.status ?? "").toUpperCase();
  return truck.isActive !== false && ["", "AVAILABLE", "READY", "IDLE"].includes(status);
}

function isOpportunity(load: Load) {
  const status = String(load.status ?? "").toUpperCase();
  return ["DRAFT", "AVAILABLE"].includes(status);
}

function buildSupportLine(load: Load) {
  const pieces: string[] = [];
  if (load.broker?.name) pieces.push(load.broker.name);
  if (load.pickupDate) pieces.push(`Pickup ${new Date(load.pickupDate).toLocaleDateString()}`);
  if (load.invoiceAmount) pieces.push(`Rate ${Number(load.invoiceAmount).toLocaleString("en-US", { style: "currency", currency: "USD" })}`);
  return pieces.join(" · ") || "Review route, timing, and fit before assigning.";
}

type CoriLoadFitFoundationProps = {
  variant?: "notifications" | "dashboard";
  maxItems?: number;
};

export function CoriLoadFitFoundation({ variant = "notifications", maxItems }: CoriLoadFitFoundationProps) {
  const [loads, setLoads] = useState<Load[]>([]);
  const [trucks, setTrucks] = useState<Truck[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let active = true;
    setLoading(true);
    Promise.all([
      apiGet<LoadsResponse>("/api/loads"),
      apiGet<TrucksResponse>("/api/trucks"),
    ])
      .then(([loadData, truckData]) => {
        if (!active) return;
        setLoads(loadData.loads ?? []);
        setTrucks((truckData.trucks ?? []).filter((truck) => truck.isActive !== false));
        setError(null);
      })
      .catch((err) => {
        if (!active) return;
        setError(err instanceof Error ? err.message : "Unable to load CORI fit suggestions");
      })
      .finally(() => {
        if (active) setLoading(false);
      });

    return () => {
      active = false;
    };
  }, []);

  const suggestions = useMemo<FitSuggestion[]>(() => {
    const openTrucks = trucks.filter(isTruckOpen);
    const opportunityLoads = loads.filter(isOpportunity);

    return opportunityLoads.slice(0, 12).map((load, index) => {
      const loadEquipment = normalizeEquipment(load.specialRequirements ?? load.notesText);
      const bestTruck = openTrucks.find((truck) => {
        const equipment = normalizeEquipment(truck.equipmentType || truck.trailerType);
        if (!loadEquipment) return true;
        return equipment.includes(loadEquipment) || loadEquipment.includes(equipment);
      }) ?? openTrucks[index % Math.max(openTrucks.length, 1)];

      const truckLine = bestTruck
        ? `${truckDriverLabel(bestTruck)} · ${bestTruck.equipmentType}`
        : "No open truck match found yet";

      const loadLine = `${routeLabel(load)} · Load ${loadLabel(load)}`;
      const supportLine = bestTruck
        ? `CORI thinks this load could fit ${truckDriverLabel(bestTruck)}. ${buildSupportLine(load)}`
        : `CORI could not find an open truck match yet. ${buildSupportLine(load)}`;

      return {
        key: load.id,
        headline: bestTruck ? "Possible load fit found" : "Review this load next",
        truckLine,
        loadLine,
        supportLine,
        loadId: load.id,
        question: bestTruck
          ? `Does ${loadLabel(load)} look like a good fit for ${truckDriverLabel(bestTruck)}?`
          : `Which truck should I consider for load ${loadLabel(load)}?`,
      };
    }).slice(0, maxItems ?? (variant === "dashboard" ? 3 : 6));
  }, [loads, trucks]);

  const isDashboard = variant === "dashboard";

  return (
    <section className={`rounded-2xl border p-4 shadow-sm ${isDashboard ? "border-blue-200 bg-blue-50/70" : "border-sky-200 bg-sky-50/70"}`}>
      <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">{isDashboard ? "CORI fit ideas" : "CORI load-fit notifications"}</div>
          <div className="mt-1 text-xs text-slate-600">{isDashboard ? "See a few load ideas CORI thinks may fit open trucks. Open Loads to review the full list." : "This is the first foundation for showing which open truck may fit a new load. CORI is not auto-assigning anything here. It is preparing suggestions so the dispatcher can review them quickly."}</div>
        </div>
        <div className="flex flex-wrap gap-2">
          <span className="rounded-full bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open trucks: {trucks.filter(isTruckOpen).length}</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Loads to review: {loads.filter(isOpportunity).length}</span>
          <Link href="/loads" className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open Loads</Link>
          <Link href="/dashboard" className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open CORI Briefing</Link>
        </div>
      </div>

      {loading ? <div className="mt-4 rounded-xl border bg-white p-4 text-sm text-slate-500">Loading CORI fit suggestions…</div> : null}
      {error ? <div className="mt-4 rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">{error}</div> : null}

      {!loading && !error ? (
        <div className="mt-4 grid gap-3 xl:grid-cols-2">
          {suggestions.length ? suggestions.map((item) => (
            <div key={item.key} className="rounded-xl border bg-white p-4">
              <div className="text-sm font-semibold text-slate-900">{item.headline}</div>
              <div className="mt-1 text-xs text-slate-700">{item.truckLine}</div>
              <div className="mt-1 text-xs text-slate-600">{item.loadLine}</div>
              <div className="mt-2 text-xs text-slate-500">{item.supportLine}</div>
              <div className="mt-3 flex flex-wrap gap-2">
                <Link href={`/loads/${item.loadId}`} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open load</Link>
                <Link href={`/dispatch?unassigned=true`} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open dispatch</Link>
                <Link href={`/cori?source=notifications&topic=load-fit&title=${encodeURIComponent("CORI load fit suggestion")}&context=${encodeURIComponent(`${item.truckLine} · ${item.loadLine}`)}&question=${encodeURIComponent(item.question)}`} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Ask CORI</Link>
              </div>
            </div>
          )) : <div className="rounded-xl border border-dashed bg-white p-4 text-sm text-slate-500 xl:col-span-2">No open load-fit suggestions are visible right now. Once new loads and open trucks are in the system, CORI suggestions will show up here.</div>}
        </div>
      ) : null}
    </section>
  );
}
