"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { apiGet, apiPost } from "@/lib/api";
import { buildCallCopilotHref } from "@/components/cori/call-copilot-support";
import type { Truck, TruckRecentLoad } from "@/types";

export type TruckMetrics = {
  totalRevenue?: string | null;
  outstandingRevenue?: string | null;
  paidRevenue?: string | null;
  dispatchFeeEarned?: string | null;
  dispatchFeeTotal?: string | null;
  totalMiles?: string | null;
  averageRpm?: string | null;
  projectedCpm?: string | null;
  actualCpm?: string | null;
  totalAccessorials?: string | null;
  totalExpenses?: string | null;
  cancelledLoads?: number | null;
  netRevenue?: string | null;
};

export type WeeklySummary = {
  weekStartDate: string;
  totalRevenue?: string | null;
  outstandingRevenue?: string | null;
  paidRevenue?: string | null;
  dispatchFeeTotal?: string | null;
  dispatchFeeEarned?: string | null;
  totalMiles?: string | null;
  averageRpm?: string | null;
  actualCpm?: string | null;
  totalAccessorials?: string | null;
  totalExpenses?: string | null;
  cancelledLoads?: number | null;
  netRevenue?: string | null;
};

export function Card({ title, children, dense = false }: { title: string; children: React.ReactNode; dense?: boolean }) {
  return (
    <section className={`rounded-2xl border border-slate-200 bg-white shadow-sm ${dense ? "p-4" : "p-5"}`}>
      <h3 className="mb-3 text-sm font-semibold uppercase tracking-wide text-slate-900">{title}</h3>
      {children}
    </section>
  );
}

export function InfoRow({ label, value }: { label: string; value?: React.ReactNode }) {
  return (
    <div className="grid grid-cols-[120px_1fr] gap-2 border-b border-slate-100 py-2 last:border-b-0">
      <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">{label}</div>
      <div className="text-sm text-slate-900">{value || "-"}</div>
    </div>
  );
}

export function SmallStat({ label, value, detail }: { label: string; value: React.ReactNode; detail?: string }) {
  return (
    <div className="rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5">
      <div className="text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500">{label}</div>
      <div className="mt-1 text-lg font-semibold leading-6 text-slate-900">{value}</div>
      {detail ? <div className="mt-1 text-[11px] leading-4 text-slate-600">{detail}</div> : null}
    </div>
  );
}

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

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

export function formatNumber(value?: string | null) {
  const amount = Number(value || 0);
  if (!Number.isFinite(amount)) return "-";
  return new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 }).format(amount);
}

export function formatMetric(value?: string | null, digits = 2) {
  const amount = Number(value || 0);
  if (!Number.isFinite(amount)) return "-";
  return amount.toFixed(digits);
}

export function formatDate(value?: string | null) {
  if (!value) return "-";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleDateString();
}

export function formatWeekRange(value?: string | null) {
  if (!value) return "No week saved";
  const start = new Date(value);
  if (Number.isNaN(start.getTime())) return value;
  const end = new Date(start);
  end.setDate(end.getDate() + 6);
  return `${start.toLocaleDateString()} - ${end.toLocaleDateString()}`;
}

export function numericValue(value?: string | null) {
  const amount = Number(value ?? null);
  return Number.isFinite(amount) ? amount : null;
}

export function deriveDispatchFee(metrics?: TruckMetrics | WeeklySummary | null) {
  return metrics?.dispatchFeeTotal ?? metrics?.dispatchFeeEarned ?? null;
}

export function deriveInvoiceRevenue(metrics?: TruckMetrics | WeeklySummary | null) {
  const totalRevenue = numericValue(metrics?.totalRevenue ?? null);
  const accessorials = numericValue(metrics?.totalAccessorials ?? null) ?? 0;
  if (totalRevenue === null) return null;
  return String(totalRevenue - accessorials);
}

export function deriveAverageRpm(metrics?: TruckMetrics | WeeklySummary | null) {
  if (metrics?.averageRpm != null) return metrics.averageRpm;
  const miles = numericValue(metrics?.totalMiles ?? null);
  const invoiceRevenue = numericValue(deriveInvoiceRevenue(metrics));
  if (!miles || miles <= 0 || invoiceRevenue === null) return null;
  return String(invoiceRevenue / miles);
}

export function deriveActualCpm(metrics?: TruckMetrics | WeeklySummary | null) {
  if (metrics?.actualCpm != null) return metrics.actualCpm;
  const miles = numericValue(metrics?.totalMiles ?? null);
  const totalExpenses = numericValue(metrics?.totalExpenses ?? null);
  if (!miles || miles <= 0 || totalExpenses === null) return null;
  return String(totalExpenses / miles);
}

export function getContinuityState(truck: Truck, linkedDrivers: number) {
  const currentLoad = truck.loads?.[0] ?? null;
  if (truck.isActive === false) {
    return {
      label: "Inactive",
      tone: "bg-slate-100 text-slate-700",
      message: "This truck is inactive until you turn it back on.",
      actionLabel: "Review truck",
    };
  }

  if (!linkedDrivers) {
    return {
      label: "At risk",
      tone: "bg-amber-100 text-amber-800",
      message: "Link a driver before this truck can move cleanly.",
      actionLabel: "Fix risk",
    };
  }

  if (!currentLoad) {
    return {
      label: "Needs next load today",
      tone: "bg-blue-100 text-blue-800",
      message: "Work the next load before this truck loses momentum.",
      actionLabel: "Work next load",
    };
  }

  if (currentLoad.status && ["DELIVERED", "COMPLETED"].includes(currentLoad.status.toUpperCase())) {
    return {
      label: "Uncovered",
      tone: "bg-red-100 text-red-800",
      message: "The last move is done. Line up the next load now.",
      actionLabel: "Work next load",
    };
  }

  return {
    label: "Protected",
    tone: "bg-emerald-100 text-emerald-800",
    message: "This truck has active work. Keep the next move protected.",
    actionLabel: "Open truck",
  };
}


function buildTruckCallHref(truck: Truck, currentLoad: TruckRecentLoad | null, purpose: string = "NEGOTIATE_RATE") {
  return buildCallCopilotHref({
    contactId: currentLoad?.broker?.id || undefined,
    contactType: currentLoad?.broker ? "broker" : undefined,
    contactName: currentLoad?.broker?.name || undefined,
    phone: undefined,
    companyLabel: currentLoad?.broker?.name || undefined,
    truckLabel: `Truck ${truck.truckNumber}`,
    laneLabel: currentLoad ? `${currentLoad.pickupLocation || "Pickup"} → ${currentLoad.deliveryLocation || "Delivery"}` : undefined,
    targetRate: currentLoad?.invoiceAmount ? String(Number(currentLoad.invoiceAmount) * 1.15) : undefined,
    floorRate: currentLoad?.invoiceAmount || undefined,
    purpose,
    source: "truck-next-load",
  });
}

export function buildActionQueue(truck: Truck, currentLoad: TruckRecentLoad | null, linkedDrivers: number) {
  const actions: { title: string; detail: string; cta: string; href: string }[] = [];

  if (!linkedDrivers) {
    actions.push({
      title: "Link a driver",
      detail: "Add or assign a driver before you dispatch from this truck.",
      cta: "Open drivers",
      href: "/drivers",
    });
  }

  if (!currentLoad) {
    actions.push({
      title: "Find next load",
      detail: "No active move is attached to this truck right now.",
      cta: "Open load search",
      href: buildTruckCallHref(truck, currentLoad),
    });
  } else {
    actions.push({
      title: "Keep the next load protected",
      detail: currentLoad.deliveryLocation ? `Current move ends at ${currentLoad.deliveryLocation}. Start working the next load now.` : "Start working the next load before this move ends.",
      cta: "Work next load",
      href: `/trucks/${truck.id}/next-load`,
    });

    actions.push({
      title: "Review current move",
      detail: `${currentLoad.pickupLocation || "Pickup"} to ${currentLoad.deliveryLocation || "Delivery"}`,
      cta: "Open current load",
      href: `/trucks/${truck.id}/current-load`,
    });

    actions.push({
      title: "Get rate con / POD",
      detail: "Keep the paperwork chain clean while the load is active.",
      cta: "Open paperwork",
      href: `/trucks/${truck.id}/documents`,
    });
  }

  return actions.slice(0, 4);
}

export function MetricCell({ label, value }: { label: string; value: string }) {
  return (
    <div className="border-r border-b border-slate-100 px-3 py-2 odd:border-r even:border-r-0 last:border-b-0">
      <div className="text-[10px] font-semibold uppercase tracking-wide text-slate-500">{label}</div>
      <div className="mt-1 text-sm font-semibold text-slate-900">{value}</div>
    </div>
  );
}

export function DashboardColumn({ title, subtitle, metrics }: { title: string; subtitle: string; metrics: TruckMetrics | WeeklySummary | null }) {
  const revenue = metrics?.totalRevenue ?? null;
  const outstanding = metrics?.outstandingRevenue ?? null;
  const paid = metrics?.paidRevenue ?? null;
  const fee = deriveDispatchFee(metrics);
  const avgRpm = deriveAverageRpm(metrics);
  const actualCpm = deriveActualCpm(metrics);

  return (
    <div className="min-w-0 rounded-xl border border-slate-200 bg-white">
      <div className="border-b border-slate-200 bg-slate-50 px-3 py-2">
        <div className="text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500">{title}</div>
        <div className="mt-1 text-xs text-slate-600">{subtitle}</div>
      </div>
      <div className="grid grid-cols-2 border-b border-slate-100 text-xs">
        <MetricCell label="Revenue" value={formatCompactMoney(revenue)} />
        <MetricCell label="Outstanding" value={formatCompactMoney(outstanding)} />
        <MetricCell label="Paid" value={formatCompactMoney(paid)} />
        <MetricCell label="Dispatch fee" value={formatCompactMoney(fee ?? null)} />
        <MetricCell label="Avg RPM" value={`$${formatMetric(avgRpm)}`} />
        <MetricCell label="Actual CPM" value={`$${formatMetric(actualCpm)}`} />
        <MetricCell label="Miles" value={formatNumber(metrics?.totalMiles ?? null)} />
        <MetricCell label="Cancelled" value={String(metrics?.cancelledLoads ?? 0)} />
        <MetricCell label="Extras" value={formatCompactMoney(metrics?.totalAccessorials ?? null)} />
        <MetricCell label="Expenses" value={formatCompactMoney(metrics?.totalExpenses ?? null)} />
      </div>
    </div>
  );
}


export function ContinuityBadge({ label, tone }: { label: string; tone?: string }) {
  return <span className={`inline-flex rounded-full px-2.5 py-1 text-xs font-semibold ${tone || "bg-slate-100 text-slate-700"}`}>{label}</span>;
}

export function getContinuityBuckets(label?: string | null) {
  const normalized = (label || "").toLowerCase();
  return {
    isProtected: normalized === "protected",
    isNeedsNextLoad: normalized === "needs next load today",
    isAtRisk: normalized === "at risk",
    isUncovered: normalized === "uncovered",
  };
}

export function buildNextMoveSummary(truck: Truck, currentLoad: TruckRecentLoad | null, continuity: ReturnType<typeof getContinuityState> | null) {
  const lane = currentLoad?.deliveryLocation || currentLoad?.pickupLocation || "Target lane not set";
  const currentStatus = currentLoad?.status?.toUpperCase() || null;
  const continuityBuckets = getContinuityBuckets(continuity?.label);

  if (continuityBuckets.isProtected && currentLoad) {
    return {
      headline: "Next move is protected",
      body: `This truck already has active work moving through ${lane}. Keep the follow-up chain tight so the next move stays protected.`,
      pickupWindow: currentLoad.deliveryDate || currentLoad.pickupDate || null,
      deliveryWindow: currentLoad.deliveryDate || null,
      brokerName: currentLoad.broker?.name || "Broker not saved",
      rate: currentLoad.invoiceAmount || null,
      lane,
      urgency: "Low",
      ctaLabel: "Keep next load protected",
    };
  }

  if (continuityBuckets.isAtRisk) {
    return {
      headline: "This truck is at risk of going empty",
      body: `A driver or load issue is holding this truck back. Work the next move now before delivery momentum is lost in ${lane}.`,
      pickupWindow: currentLoad?.deliveryDate || null,
      deliveryWindow: currentLoad?.deliveryDate || null,
      brokerName: currentLoad?.broker?.name || "Broker call needed",
      rate: currentLoad?.invoiceAmount || null,
      lane,
      urgency: "High",
      ctaLabel: "Fix risk now",
    };
  }

  if (continuityBuckets.isUncovered || (currentStatus != null && ["DELIVERED", "COMPLETED"].includes(currentStatus))) {
    return {
      headline: "No next move is locked yet",
      body: `The last move is effectively done. Work a replacement load now and protect the next lane before this truck sits after ${lane}.`,
      pickupWindow: null,
      deliveryWindow: currentLoad?.deliveryDate || null,
      brokerName: currentLoad?.broker?.name || "No broker locked",
      rate: null,
      lane,
      urgency: "Urgent",
      ctaLabel: "Find next load now",
    };
  }

  return {
    headline: "Work the next load today",
    body: `This truck still has movement, but the next move is not fully protected. Start covering the next lane around ${lane} now.`,
    pickupWindow: currentLoad?.deliveryDate || null,
    deliveryWindow: currentLoad?.deliveryDate || null,
    brokerName: currentLoad?.broker?.name || "Broker call needed",
    rate: currentLoad?.invoiceAmount || null,
    lane,
    urgency: "Today",
    ctaLabel: "Work next load",
  };
}

export function buildContinuityActionQueue(truck: Truck, currentLoad: TruckRecentLoad | null, continuity: ReturnType<typeof getContinuityState> | null) {
  const summary = buildNextMoveSummary(truck, currentLoad, continuity);
  const actions = [
    {
      title: summary.ctaLabel,
      detail: summary.body,
      cta: summary.ctaLabel,
      href: buildTruckCallHref(truck, currentLoad),
    },
    {
      title: "Review load options",
      detail: `Use CORI Quotes and target the lane around ${summary.lane}.`,
      cta: "Open CORI Quotes",
      href: "/cori/quotes",
    },
    {
      title: "Check broker follow-up",
      detail: `${summary.brokerName} is the current broker for this truck's active move.`,
      cta: "Open follow-ups",
      href: "/dispatch",
    },
    {
      title: "Keep the driver ready",
      detail: "Make sure the driver has the next move plan before the current move ends.",
      cta: "Open drivers",
      href: "/drivers",
    },
  ];
  return actions;
}


export function buildBrokerCallContinuity(truck: Truck, currentLoad: TruckRecentLoad | null, continuity: ReturnType<typeof getContinuityState> | null) {
  const continuityBuckets = getContinuityBuckets(continuity?.label);
  const brokerName = currentLoad?.broker?.name || "Broker not saved yet";
  const lane = currentLoad?.deliveryLocation || currentLoad?.pickupLocation || "target lane";
  const anchorRate = currentLoad?.invoiceAmount || null;

  if (continuityBuckets.isProtected) {
    return {
      outcome: "Booked",
      note: `The next move is protected. Keep ${brokerName} warm and confirm the next details before delivery in ${lane}.`,
      nextStep: "Confirm pickup plan",
      callback: "No callback due",
      primaryAction: { label: "Mark booked", href: `/trucks/${truck.id}/next-load` },
      secondaryAction: { label: "Call broker", href: buildTruckCallHref(truck, currentLoad) },
      anchorRate,
      brokerName,
    };
  }

  if (continuityBuckets.isAtRisk) {
    return {
      outcome: "Retry now",
      note: `This truck is at risk. Rework the broker conversation now and try to protect the lane before delivery momentum is lost in ${lane}.`,
      nextStep: "Retry broker call",
      callback: "Callback due now",
      primaryAction: { label: "Retry", href: buildTruckCallHref(truck, currentLoad, "CALLBACK") },
      secondaryAction: { label: "Set callback", href: "/dispatch" },
      anchorRate,
      brokerName,
    };
  }

  if (continuityBuckets.isUncovered) {
    return {
      outcome: "Pass and move on",
      note: `No next move is locked yet. Pass on weak options fast and move to the next broker before this truck sits after ${lane}.`,
      nextStep: "Work a new broker now",
      callback: "No good callback saved",
      primaryAction: { label: "Find another load", href: "/cori/quotes" },
      secondaryAction: { label: "Call broker", href: buildTruckCallHref(truck, currentLoad) },
      anchorRate,
      brokerName,
    };
  }

  return {
    outcome: "Callback pending",
    note: `The next move still needs to be protected. Keep the broker follow-up active and work the next lane around ${lane}.`,
    nextStep: "Set callback or book",
    callback: "Callback due today",
    primaryAction: { label: "Set callback", href: "/dispatch" },
    secondaryAction: { label: "Call broker", href: buildTruckCallHref(truck, currentLoad) },
    anchorRate,
    brokerName,
  };
}

export function TruckSubnav({ truckId }: { truckId: string }) {
  const pathname = usePathname();
  const items = [
    { href: `/trucks/${truckId}`, label: "Overview" },
    { href: `/trucks/${truckId}/current-load`, label: "Current Load" },
    { href: `/trucks/${truckId}/next-load`, label: "Next Load" },
    { href: `/trucks/${truckId}/money`, label: "Money" },
    { href: `/trucks/${truckId}/documents`, label: "Paperwork" },
    { href: `/trucks/${truckId}/history`, label: "History" },
  ];

  return (
    <nav className="flex flex-wrap gap-2 rounded-2xl border border-slate-200 bg-white p-2 shadow-sm">
      {items.map((item) => {
        const active = pathname === item.href;
        return (
          <Link
            key={item.href}
            href={item.href}
            className={`rounded-xl px-3 py-2 text-sm font-medium ${active ? "bg-slate-950 text-white" : "bg-slate-50 text-slate-700 hover:bg-slate-100"}`}
          >
            {item.label}
          </Link>
        );
      })}
    </nav>
  );
}

export function useTruckCommandData(truckId?: string) {
  const [truck, setTruck] = useState<Truck | null>(null);
  const [ytdMetrics, setYtdMetrics] = useState<TruckMetrics | null>(null);
  const [rollingMetrics, setRollingMetrics] = useState<TruckMetrics | null>(null);
  const [weeklySummaries, setWeeklySummaries] = useState<WeeklySummary[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [working, setWorking] = useState(false);

  async function loadTruck() {
    if (!truckId) return;

    try {
      setError(null);
      const [truckData, ytdData, rollingData, weeklyData] = await Promise.all([
        apiGet<{ truck: Truck }>(`/api/trucks/${truckId}`),
        apiGet<{ metrics: TruckMetrics | null }>(`/api/trucks/${truckId}/metrics?periodType=YTD`),
        apiGet<{ metrics: TruckMetrics | null }>(`/api/trucks/${truckId}/metrics?periodType=WEEKLY`),
        apiGet<{ summaries: WeeklySummary[] }>(`/api/trucks/${truckId}/weekly-summaries`),
      ]);
      setTruck(truckData.truck);
      setYtdMetrics(ytdData.metrics ?? null);
      setRollingMetrics(rollingData.metrics ?? null);
      setWeeklySummaries(weeklyData.summaries ?? []);
    } catch (err: any) {
      setError(err?.message ?? "Failed to load truck");
    }
  }

  useEffect(() => {
    loadTruck();
  }, [truckId]);

  async function toggleActive() {
    if (!truck) return;
    try {
      setWorking(true);
      setError(null);
      await apiPost(`/api/trucks/${truck.id}/${truck.isActive === false ? "reactivate" : "deactivate"}`, {});
      await loadTruck();
    } catch (err: any) {
      setError(err?.message ?? "Unable to update truck state");
    } finally {
      setWorking(false);
    }
  }

  const linkedDrivers = truck?.drivers?.length ?? 0;
  const currentLoad = truck?.loads?.[0] ?? null;
  const recentLoads = truck?.loads?.length ?? 0;
  const identityLabel = [truck?.year, truck?.make, truck?.model].filter(Boolean).join(" ") || truck?.equipmentType || "-";
  const continuity = truck ? getContinuityState(truck, linkedDrivers) : null;
  const actionQueue = useMemo(() => (truck ? buildActionQueue(truck, currentLoad, linkedDrivers) : []), [truck, currentLoad, linkedDrivers]);
  const weeklyCompleted = weeklySummaries[0] ?? null;
  const quickSnapshot = {
    followUps: actionQueue.length,
    missingDocs: currentLoad ? 2 : 0,
    openIssues: continuity?.label === "At risk" || continuity?.label === "Uncovered" ? 1 : 0,
    continuity: continuity?.label || "-",
  };
  const currentWeekLabel = "Current week so far";
  const currentWeekSubtext = "Monday through today";

  return {
    truck,
    ytdMetrics,
    rollingMetrics,
    weeklySummaries,
    weeklyCompleted,
    error,
    working,
    linkedDrivers,
    currentLoad,
    recentLoads,
    identityLabel,
    continuity,
    actionQueue,
    quickSnapshot,
    currentWeekLabel,
    currentWeekSubtext,
    loadTruck,
    toggleActive,
  };
}
