"use client";

import Link from "next/link";
import { ChangeEvent, ReactNode, useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import { PageHeader } from "@/components/ui/page-header";
import { PlanFeatureGate } from "@/components/subscriptions/plan-feature-gate";
import { apiGet, apiPost } from "@/lib/api";
import type { Load } from "@/types";

type ChatRole = "assistant" | "user";

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

type ParsedDocument = {
  fileName: string;
  documentType: "Rate Confirmation" | "Bill of Lading" | "Proof of Delivery" | "Invoice / Billing" | "Unknown";
  extracted: {
    broker?: string | null;
    pickup?: string | null;
    delivery?: string | null;
    loadRef?: string | null;
    truck?: string | null;
    driver?: string | null;
    rate?: string | null;
    deliveryDate?: string | null;
    invoiceDate?: string | null;
  };
  suggestedAction: string;
  suggestedStage: string;
  confidence: string;
  reviewNote: string;
};

type LoadStatus = "DRAFT" | "AVAILABLE" | "ASSIGNED" | "IN_TRANSIT" | "DELIVERED" | "INVOICED" | "PAID_FULL" | "CANCELLED";

type CoriMatchedLoad = {
  id: string;
  referenceNumber?: string | null;
  status: string;
  pickupLocation?: string | null;
  deliveryLocation?: string | null;
  truck?: { truckNumber: string } | null;
  driver?: { firstName?: string | null; lastName?: string | null } | null;
};

function formatDriver(driver?: { firstName?: string | null; lastName?: string | null } | null) {
  const parts = [driver?.firstName, driver?.lastName].filter(Boolean);
  return parts.length ? parts.join(" ") : null;
}

function formatLoadContext(load: CoriMatchedLoad | null) {
  if (!load) return "No matching load found yet";
  const bits = [
    load.truck?.truckNumber ? `Truck ${load.truck.truckNumber}` : null,
    formatDriver(load.driver),
    load.pickupLocation || load.deliveryLocation ? `${load.pickupLocation ?? "Unknown pickup"} to ${load.deliveryLocation ?? "Unknown delivery"}` : null,
  ].filter(Boolean);
  return bits.length ? bits.join(" · ") : (load.referenceNumber ?? "Matching load found");
}

function getSuggestedStatus(documentType: ParsedDocument["documentType"]): LoadStatus | null {
  if (documentType === "Bill of Lading") return "IN_TRANSIT";
  if (documentType === "Proof of Delivery") return "DELIVERED";
  if (documentType === "Invoice / Billing") return "INVOICED";
  return null;
}

function getStatusLabel(status: string | null) {
  const labels: Record<string, string> = {
    DRAFT: "Draft",
    AVAILABLE: "Available",
    ASSIGNED: "Assigned",
    IN_TRANSIT: "In Transit",
    DELIVERED: "Delivered",
    INVOICED: "Invoiced",
    PAID_FULL: "Paid in Full",
    CANCELLED: "Cancelled",
  };
  return status ? (labels[status] ?? status) : "Unknown";
}

function canMoveToSuggestedStage(currentStatus: string | null | undefined, nextStatus: LoadStatus | null) {
  if (!currentStatus || !nextStatus) return false;
  const allowed: Record<string, LoadStatus[]> = {
    DRAFT: ["AVAILABLE", "ASSIGNED", "CANCELLED"],
    AVAILABLE: ["ASSIGNED", "CANCELLED"],
    ASSIGNED: ["IN_TRANSIT", "CANCELLED"],
    IN_TRANSIT: ["DELIVERED", "CANCELLED"],
    DELIVERED: ["INVOICED"],
    INVOICED: ["PAID_FULL"],
    PAID_FULL: [],
    CANCELLED: [],
  };
  return (allowed[currentStatus] ?? []).includes(nextStatus);
}

const DEFAULT_FAVORITE_PROMPTS = [
  "What should I check before assigning this load?",
  "What is the safest next dispatcher step?",
  "Summarize this in plain language.",
  "What should I do after delivery?",
];

const EMPTY_CHAT_MESSAGE = "Ask CORI your question and keep it simple. One job, one answer, one next step.";

type UtilityTray = "favorites" | "history" | "document" | "help" | null;

type ConversationSnapshot = {
  id: string;
  title: string;
  updatedAt: string;
  messages: ChatMessage[];
};


function UtilityIcon({ children }: { children: ReactNode }) {
  return <span className="pointer-events-none inline-flex h-4 w-4 items-center justify-center">{children}</span>;
}

function FavoritesIcon() {
  return <UtilityIcon><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-4 w-4"><path strokeLinecap="round" strokeLinejoin="round" d="m12 3 2.8 5.67 6.26.91-4.53 4.41 1.07 6.24L12 17.3 6.4 20.23l1.07-6.24L2.94 9.58l6.26-.91L12 3Z"/></svg></UtilityIcon>;
}

function HistoryIcon() {
  return <UtilityIcon><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-4 w-4"><path strokeLinecap="round" strokeLinejoin="round" d="M3 12a9 9 0 1 0 3-6.71"/><path strokeLinecap="round" strokeLinejoin="round" d="M3 4v5h5"/><path strokeLinecap="round" strokeLinejoin="round" d="M12 7v5l3 2"/></svg></UtilityIcon>;
}

function AttachmentIcon() {
  return <UtilityIcon><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-4 w-4"><path strokeLinecap="round" strokeLinejoin="round" d="m16.5 6.5-6.9 6.9a3 3 0 1 0 4.24 4.24l7.42-7.43a5 5 0 1 0-7.07-7.07L6.5 11.82"/></svg></UtilityIcon>;
}

function HelpIcon() {
  return <UtilityIcon><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-4 w-4"><circle cx="12" cy="12" r="9"/><path strokeLinecap="round" strokeLinejoin="round" d="M9.75 9a2.25 2.25 0 1 1 3.86 1.57c-.8.78-1.36 1.3-1.36 2.43"/><circle cx="12" cy="17" r=".8" fill="currentColor" stroke="none"/></svg></UtilityIcon>;
}

function SaveIcon() {
  return <UtilityIcon><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-4 w-4"><path strokeLinecap="round" strokeLinejoin="round" d="M5 4h11l3 3v13H5z"/><path strokeLinecap="round" strokeLinejoin="round" d="M8 4v6h8V4"/><path strokeLinecap="round" strokeLinejoin="round" d="M9 16h6"/></svg></UtilityIcon>;
}

function ClearIcon() {
  return <UtilityIcon><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-4 w-4"><path strokeLinecap="round" strokeLinejoin="round" d="M6 6l12 12M18 6 6 18"/></svg></UtilityIcon>;
}

function findValue(text: string, patterns: RegExp[]) {
  for (const pattern of patterns) {
    const match = text.match(pattern);
    if (match?.[1]) return match[1].trim();
  }
  return null;
}

function detectDocumentType(fileName: string, text: string): ParsedDocument["documentType"] {
  const full = `${fileName} ${text}`.toLowerCase();
  if (full.includes("rate con") || full.includes("rate confirmation") || full.includes("rateconf")) return "Rate Confirmation";
  if (full.includes("proof of delivery") || /\bpod\b/.test(full)) return "Proof of Delivery";
  if (full.includes("bill of lading") || /\bbol\b/.test(full)) return "Bill of Lading";
  if (full.includes("invoice") || full.includes("billing")) return "Invoice / Billing";
  return "Unknown";
}

function parseDocument(fileName: string, text: string): ParsedDocument {
  const documentType = detectDocumentType(fileName, text);
  const normalized = text.replace(/\s+/g, " ").trim();

  const broker = findValue(normalized, [
    /broker[:\-]\s*([^|,;]+)/i,
    /carrier pays?[:\-]\s*([^|,;]+)/i,
    /logistics[:\-]\s*([^|,;]+)/i,
  ]);

  const pickup = findValue(normalized, [
    /pickup[:\-]\s*([^|;]+)/i,
    /origin[:\-]\s*([^|;]+)/i,
    /from\s+([^|;]+?)\s+to\s+/i,
  ]);

  const delivery = findValue(normalized, [
    /delivery[:\-]\s*([^|;]+)/i,
    /destination[:\-]\s*([^|;]+)/i,
    /to\s+([^|;]+)/i,
  ]);

  const loadRef = findValue(normalized, [
    /load(?:\s*(?:ref|#|number))?[:\-]\s*([A-Z0-9\-]+)/i,
    /reference[:\-]\s*([A-Z0-9\-]+)/i,
    /\b(REF\-[A-Z0-9\-]+)\b/i,
  ]);

  const truck = findValue(normalized, [
    /truck[:\-]\s*([A-Z0-9\-]+)/i,
    /unit[:\-]\s*([A-Z0-9\-]+)/i,
  ]);

  const driver = findValue(normalized, [
    /driver[:\-]\s*([^|,;]+)/i,
  ]);

  const rate = findValue(normalized, [
    /rate[:\-]\s*(\$?[0-9,]+(?:\.[0-9]{2})?)/i,
    /total[:\-]\s*(\$?[0-9,]+(?:\.[0-9]{2})?)/i,
  ]);

  const deliveryDate = findValue(normalized, [
    /delivered(?:\s*on)?[:\-]\s*([A-Za-z0-9,\/\- ]+)/i,
    /delivery date[:\-]\s*([A-Za-z0-9,\/\- ]+)/i,
  ]);

  const invoiceDate = findValue(normalized, [
    /invoice(?:\s*date)?[:\-]\s*([A-Za-z0-9,\/\- ]+)/i,
  ]);

  let suggestedAction = "Needs dispatcher review";
  let suggestedStage = "Review first";
  let confidence = "Low";
  let reviewNote = "CORI found some useful details, but a dispatcher should review them before making changes.";

  if (documentType === "Rate Confirmation") {
    suggestedAction = loadRef ? "Check for a matching load, then create or update a load draft" : "Create a new load draft";
    suggestedStage = "Draft / Ready to assign";
    confidence = pickup && delivery ? "High" : "Medium";
    reviewNote = "Best next step: review the broker, route, and rate, then decide whether this should become a new load or update an existing one.";
  } else if (documentType === "Bill of Lading") {
    suggestedAction = "Match this to the right load and review shipment details";
    suggestedStage = "Assigned / In Transit";
    confidence = pickup || delivery ? "Medium" : "Low";
    reviewNote = "Best next step: check that the truck, route, and load reference match the correct load before moving the stage forward.";
  } else if (documentType === "Proof of Delivery") {
    suggestedAction = "Match this to the delivered load and review delivery confirmation";
    suggestedStage = "Delivered / Ready for invoice";
    confidence = deliveryDate || loadRef ? "High" : "Medium";
    reviewNote = "Best next step: confirm delivery details, then move the load to delivered or invoice-ready if everything matches.";
  } else if (documentType === "Invoice / Billing") {
    suggestedAction = "Match this to the load and review billing follow-up";
    suggestedStage = "Invoiced / Billing follow-up";
    confidence = invoiceDate || rate ? "Medium" : "Low";
    reviewNote = "Best next step: confirm the load, amount, and invoice timing before marking the billing stage.";
  }

  return {
    fileName,
    documentType,
    extracted: { broker, pickup, delivery, loadRef, truck, driver, rate, deliveryDate, invoiceDate },
    suggestedAction,
    suggestedStage,
    confidence,
    reviewNote,
  };
}


function buildIntroMessage(contextTitle?: string | null, contextDetail?: string | null) {
  return contextTitle || contextDetail
    ? `I am ready to help with ${contextTitle?.toLowerCase() ?? "this work"}. Ask what it means, what to check, or what to do next.`
    : "Ask your question and CORI will keep the answer focused on the dispatcher action, the risk, and the next step.";
}

function generateCoriReply(prompt: string) {
  const text = prompt.trim().toLowerCase();

  if (text.includes("next truck") || text.includes("which truck")) {
    return "Start with the truck that has the strongest combination of urgency, revenue risk, and follow-up issues. Check trucks with overdue assignment, late delivery risk, missing paperwork, or loads close to invoice-ready so the work keeps moving.";
  }

  if (text.includes("assign") && text.includes("load")) {
    return "Before assigning a load, confirm pickup, delivery, rate, appointment time, truck, driver, equipment fit, paperwork, and safety issues.";
  }

  if (text.includes("warning") || text.includes("alert")) {
    return "Treat the warning as important until you know whether it affects timing, paperwork, billing, or the truck. Confirm what changed, then reassign, follow up, or escalate.";
  }

  if (text.includes("after delivery") || text.includes("delivered")) {
    return "After delivery, confirm proof of delivery, update the load stage, review accessorials, prepare invoice follow-up, and make sure any missing paperwork is requested before billing slows down.";
  }

  if (text.includes("unpaid") || text.includes("payment")) {
    return "For unpaid loads, confirm invoice status, delivery proof, invoice date, due date, and any missing broker paperwork. Then send a precise follow-up with the load reference, amount due, and supporting documents.";
  }

  if (text.includes("document") || text.includes("rate confirmation") || text.includes("pod") || text.includes("invoice") || text.includes("bol")) {
    return "Use the document details to identify the right load, confirm what stage the load should be in, and review the suggested next step before making any record changes.";
  }

  if (text.includes("email") || text.includes("mailbox") || text.includes("brokers send")) {
    return "Ask brokers to send rate confirmations, revisions, PODs, invoices, and other load paperwork to the CORI mailbox so the dispatcher can review a prepared next-step suggestion instead of sorting every attachment manually.";
  }

  return "CORI can help you think through the next dispatcher action. Ask about the warning, document, load stage, billing follow-up, or the truck you are working on, and I will break it down step by step.";
}

export default function CoriPage() {
  const searchParams = useSearchParams();
  const source = searchParams.get("source")?.trim() || null;
  const topic = searchParams.get("topic")?.trim() || null;
  const backTo = searchParams.get("backTo")?.trim() || null;
  const contextTitle = searchParams.get("title")?.trim() || null;
  const contextDetail = searchParams.get("context")?.trim() || null;
  const initialQuestion = searchParams.get("question")?.trim() || "";

  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState(initialQuestion);
  const [uploadStatus, setUploadStatus] = useState("No document uploaded yet.");
  const [uploadedDocument, setUploadedDocument] = useState<ParsedDocument | null>(null);
  const [matchingLoad, setMatchingLoad] = useState<CoriMatchedLoad | null>(null);
  const [matchStatus, setMatchStatus] = useState("Upload a document and CORI will check for a likely load match.");
  const [isCheckingMatches, setIsCheckingMatches] = useState(false);
  const [stageActionStatus, setStageActionStatus] = useState("");
  const [isApplyingStageUpdate, setIsApplyingStageUpdate] = useState(false);
  const [favoritePrompts, setFavoritePrompts] = useState<string[]>(DEFAULT_FAVORITE_PROMPTS);
  const [recentPrompts, setRecentPrompts] = useState<string[]>([]);
  const [conversationHistory, setConversationHistory] = useState<ConversationSnapshot[]>([]);
  const [utilityTray, setUtilityTray] = useState<UtilityTray>(null);
  const [creditsRemaining] = useState(120);
  const [lastUploadedFileName, setLastUploadedFileName] = useState<string | null>(null);

  useEffect(() => {
    if (typeof window === "undefined") return;

    const savedFavorites = window.localStorage.getItem("dispatchspot-cori-favorites-v204");
    if (savedFavorites) {
      try {
        const parsed = JSON.parse(savedFavorites);
        if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) {
          setFavoritePrompts(parsed.slice(0, 12));
        }
      } catch {
        // ignore invalid saved favorites
      }
    }

    const savedPrompts = window.localStorage.getItem("dispatchspot-cori-recent-prompts-v204");
    if (savedPrompts) {
      try {
        const parsed = JSON.parse(savedPrompts);
        if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) {
          setRecentPrompts(parsed.slice(0, 12));
        }
      } catch {
        // ignore invalid recent prompts
      }
    }

    const savedHistory = window.localStorage.getItem("dispatchspot-cori-history-v204");
    if (savedHistory) {
      try {
        const parsed = JSON.parse(savedHistory);
        if (Array.isArray(parsed)) {
          setConversationHistory(parsed.slice(0, 8));
        }
      } catch {
        // ignore invalid saved history
      }
    }

    if (!initialQuestion) return;
    const timer = window.setTimeout(() => {
      sendPrompt(initialQuestion);
    }, 80);
    return () => window.clearTimeout(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;
    window.localStorage.setItem("dispatchspot-cori-favorites-v204", JSON.stringify(favoritePrompts));
  }, [favoritePrompts]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    window.localStorage.setItem("dispatchspot-cori-recent-prompts-v204", JSON.stringify(recentPrompts));
  }, [recentPrompts]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    window.localStorage.setItem("dispatchspot-cori-history-v204", JSON.stringify(conversationHistory));
  }, [conversationHistory]);

  function buildConversationTitle(nextMessages: ChatMessage[]) {
    const firstUser = nextMessages.find((message) => message.role === "user")?.content?.trim();
    if (!firstUser) return contextTitle ?? "New CORI conversation";
    return firstUser.length > 64 ? `${firstUser.slice(0, 61)}...` : firstUser;
  }

  function persistConversation(nextMessages: ChatMessage[]) {
    if (!nextMessages.length) {
      setConversationHistory([]);
      return;
    }

    const snapshot: ConversationSnapshot = {
      id: `conversation-${Date.now()}`,
      title: buildConversationTitle(nextMessages),
      updatedAt: new Date().toISOString(),
      messages: nextMessages.slice(-20),
    };

    setConversationHistory((current) => [snapshot, ...current.filter((item) => item.title !== snapshot.title)].slice(0, 8));
  }

  function restoreConversation(snapshot: ConversationSnapshot) {
    setMessages(snapshot.messages);
    setUtilityTray(null);
  }

  function removeFavorite(promptToRemove: string) {
    setFavoritePrompts((current) => current.filter((prompt) => prompt !== promptToRemove));
  }

  function removeHistoryConversation(id: string) {
    setConversationHistory((current) => current.filter((item) => item.id !== id));
  }

  async function findMatchingLoad(parsed: ParsedDocument) {
    setIsCheckingMatches(true);
    setMatchStatus("Checking current loads for the best match...");
    setMatchingLoad(null);
    setStageActionStatus("");

    try {
      const loads = await apiGet<Load[]>("/api/loads");
      const normalizedReference = parsed.extracted.loadRef?.toLowerCase() ?? null;
      const normalizedPickup = parsed.extracted.pickup?.toLowerCase() ?? null;
      const normalizedDelivery = parsed.extracted.delivery?.toLowerCase() ?? null;
      const normalizedTruck = parsed.extracted.truck?.toLowerCase() ?? null;
      const normalizedDriver = parsed.extracted.driver?.toLowerCase() ?? null;

      const scored = loads
        .map((load) => {
          let score = 0;
          if (normalizedReference && load.referenceNumber?.toLowerCase() === normalizedReference) score += 7;
          if (normalizedPickup && load.pickupLocation?.toLowerCase().includes(normalizedPickup)) score += 2;
          if (normalizedDelivery && load.deliveryLocation?.toLowerCase().includes(normalizedDelivery)) score += 2;
          if (normalizedTruck && load.truck?.truckNumber?.toLowerCase() === normalizedTruck) score += 3;
          const driverName = `${load.driver?.firstName ?? ""} ${load.driver?.lastName ?? ""}`.trim().toLowerCase();
          if (normalizedDriver && driverName.includes(normalizedDriver)) score += 2;
          return { load, score };
        })
        .filter((entry) => entry.score > 0)
        .sort((a, b) => b.score - a.score);

      if (!scored.length) {
        setMatchStatus("No likely match found in the current loads. A dispatcher should review before creating or changing anything.");
        return;
      }

      const best = scored[0].load as CoriMatchedLoad;
      setMatchingLoad(best);
      setMatchStatus(`CORI found a likely match: ${best.referenceNumber ?? "Unnamed load"}. Review it before making changes.`);
    } catch {
      setMatchStatus("CORI could not check current loads right now. The dispatcher should review manually.");
    } finally {
      setIsCheckingMatches(false);
    }
  }

  async function applySuggestedStageUpdate() {
    if (!uploadedDocument || !matchingLoad) return;
    const nextStatus = getSuggestedStatus(uploadedDocument.documentType);
    if (!nextStatus) {
      setStageActionStatus("This document type does not suggest a stage change yet.");
      return;
    }

    if (!canMoveToSuggestedStage(matchingLoad.status, nextStatus)) {
      setStageActionStatus(`CORI recommends review only. This load cannot move from ${getStatusLabel(matchingLoad.status)} to ${getStatusLabel(nextStatus)} in one step.`);
      return;
    }

    setIsApplyingStageUpdate(true);
    setStageActionStatus("Applying dispatcher-approved stage update...");

    try {
      await apiPost(`/api/loads/${matchingLoad.id}/status`, { status: nextStatus });
      setMatchingLoad((current) => (current ? { ...current, status: nextStatus } : current));
      setStageActionStatus(`Load moved to ${getStatusLabel(nextStatus)}. Review the load detail page for any remaining follow-up.`);
      setMessages((current) => {
        const nextMessages = [
          ...current,
          {
            id: `stage-update-${Date.now()}`,
            role: "assistant" as const,
            content: `Approved update applied. The matching load is now marked ${getStatusLabel(nextStatus)}.`,
          },
        ];
        persistConversation(nextMessages);
        return nextMessages;
      });
    } catch {
      setStageActionStatus("CORI could not apply that stage update right now. Please try again.");
    } finally {
      setIsApplyingStageUpdate(false);
    }
  }

  function sendPrompt(promptText: string) {
    const trimmed = promptText.trim();
    if (!trimmed) return;

    const reply = generateCoriReply(trimmed);
    setMessages((current) => {
      const nextMessages = [
        ...current,
        { id: `user-${Date.now()}`, role: "user" as const, content: trimmed },
        { id: `assistant-${Date.now() + 1}`, role: "assistant" as const, content: reply },
      ];
      persistConversation(nextMessages);
      return nextMessages;
    });
    setRecentPrompts((current) => [trimmed, ...current.filter((item) => item !== trimmed)].slice(0, 6));
    setInput("");
    setUtilityTray(null);
  }

  function insertPrompt(prompt: string) {
    setInput(prompt);
    setUtilityTray(null);
  }

  function saveCurrentPrompt() {
    const trimmed = input.trim();
    if (!trimmed) return;
    setFavoritePrompts((current) => [trimmed, ...current.filter((item) => item !== trimmed)].slice(0, 8));
    setUtilityTray("favorites");
  }

  function clearConversation() {
    setMessages([]);
    setInput("");
  }

  async function handleDocumentUpload(file: File | null) {
    if (!file) return;
    setLastUploadedFileName(file.name);
    setUploadStatus(`Reading ${file.name}...`);
    setStageActionStatus("");

    try {
      const text = await file.text();
      const parsed = parseDocument(file.name, text);
      setUploadedDocument(parsed);
      setUploadStatus(`${parsed.documentType} detected. CORI prepared a supervised suggestion for the dispatcher to review.`);
      void findMatchingLoad(parsed);
      setMessages((current) => {
        const nextMessages = [
          ...current,
          { id: `upload-user-${Date.now()}`, role: "user" as const, content: `Please review this document: ${file.name}` },
          {
            id: `upload-assistant-${Date.now() + 1}`,
            role: "assistant" as const,
            content: [
              `I found a ${parsed.documentType}.`,
              parsed.extracted.loadRef ? `Load: ${parsed.extracted.loadRef}` : null,
              parsed.extracted.pickup || parsed.extracted.delivery ? `Route: ${parsed.extracted.pickup ?? "Unknown pickup"} to ${parsed.extracted.delivery ?? "Unknown delivery"}` : null,
              `Suggested action: ${parsed.suggestedAction}.`,
              `Suggested stage: ${parsed.suggestedStage}.`,
              `Dispatcher review: required before any record is created or updated.`,
            ].filter(Boolean).join("\n\n"),
          },
        ];
        persistConversation(nextMessages);
        return nextMessages;
      });
    } catch {
      setUploadStatus("CORI could not read that file. Try again or upload a text-based document.");
    }
  }

  const contextChips = [
    source ? `Opened from ${source.replaceAll("-", " ")}` : null,
    topic ? `Topic: ${topic}` : null,
    contextTitle ? contextTitle : null,
  ].filter(Boolean) as string[];

  const supportPrompts = contextTitle || contextDetail
    ? [
        initialQuestion || `What should I do next with ${contextTitle ?? "this"}?`,
        "What should I check first?",
        "Explain the risk here.",
        "Give me the safest next step.",
      ].filter((value, index, array) => value && array.indexOf(value) === index)
    : [];

  const conversationCount = messages.filter((message) => message.role === "user").length;


  const creditTone = useMemo(() => {
    if (creditsRemaining <= 20) return "text-rose-600";
    if (creditsRemaining <= 50) return "text-amber-600";
    return "text-slate-600";
  }, [creditsRemaining]);

  function handleFilePickerChange(event: ChangeEvent<HTMLInputElement>) {
    void handleDocumentUpload(event.target.files?.[0] ?? null);
    event.target.value = "";
  }

  return (
    <PlanFeatureGate feature="cori">
      <div className="space-y-6">
      <PageHeader
        title="Ask CORI"
        subtitle={contextTitle ? `Focused help for ${contextTitle.toLowerCase()}. Ask one direct question and CORI will answer in dispatcher language.` : "A clean dispatcher chat surface for quick, focused guidance."}
        action={
          <div className="flex flex-wrap items-center gap-2 text-xs">
            <div className={`rounded-full border bg-white px-3 py-1.5 font-medium ${creditTone}`}>
              {creditsRemaining} CORI credits left
            </div>
            <button type="button" className="rounded-full px-2 py-1 font-medium text-slate-500 hover:text-slate-900">Add credits</button>
          </div>
        }
      />

      <div className="mx-auto max-w-5xl">
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
          <div className="flex flex-wrap gap-2 text-xs text-slate-500">
            {contextChips.map((chip) => (
              <span key={chip} className="rounded-full border bg-white px-3 py-1.5 font-medium text-slate-600">
                {chip}
              </span>
            ))}
          </div>
          <div className="flex flex-wrap items-center gap-2 text-xs text-slate-500">
            <span className="rounded-full border bg-white px-3 py-1.5 font-medium text-slate-600">{conversationCount} questions this conversation</span>
            {backTo ? <Link href={backTo} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50">Go back</Link> : null}
          </div>
        </div>

        <section className="overflow-hidden rounded-[32px] border bg-white shadow-sm">
          <div className="px-4 py-5 sm:px-6 sm:py-6">
            <div className="min-h-[360px] rounded-[28px] bg-slate-50/70 p-4 sm:p-6">
              <div className="mx-auto flex max-w-3xl flex-col gap-4">
                {!messages.length ? (
                  <div className="flex min-h-[280px] items-center justify-center">
                    <div className="max-w-xl text-center">
                      <div className="text-xs font-semibold uppercase tracking-[0.24em] text-slate-400">Ask CORI</div>
                      <p className="mt-4 text-[26px] font-medium tracking-tight text-slate-950 sm:text-[28px]">One question at a time.</p>
                      <p className="mt-3 text-sm text-slate-500">{EMPTY_CHAT_MESSAGE}</p>
                      <p className="mt-5 text-xs text-slate-400">Keep it direct. CORI will answer with the next step.</p>
                    </div>
                  </div>
                ) : null}
                {messages.map((message) => (
                  <div key={message.id} className={`flex ${message.role === "user" ? "justify-end" : "justify-start"}`}>
                    <div className={`max-w-[92%] sm:max-w-[88%] ${message.role === "user" ? "items-end" : "items-start"} flex flex-col`}>
                      <div className={`mb-1.5 px-1 text-[11px] font-medium ${message.role === "user" ? "text-slate-500" : "text-sky-700"}`}>
                        {message.role === "user" ? "You" : "CORI"}
                      </div>
                      <div
                        className={`rounded-[24px] px-4 py-3 text-sm whitespace-pre-line shadow-sm sm:px-5 sm:py-4 ${
                          message.role === "user"
                            ? "bg-slate-950 text-white"
                            : "border border-slate-200 bg-white text-slate-800 ring-1 ring-slate-100"
                        }`}
                      >
                        {message.content}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <form
              onSubmit={(event) => {
                event.preventDefault();
                sendPrompt(input);
              }}
              className="sticky bottom-0 z-10 mx-auto mt-5 max-w-3xl pb-1"
            >
              <label htmlFor="cori-input" className="sr-only">
                Ask CORI
              </label>
              <div className="overflow-hidden rounded-[30px] border bg-white shadow-sm">
                <textarea
                  id="cori-input"
                  value={input}
                  onChange={(event) => setInput(event.target.value)}
                  rows={2}
                  placeholder="Ask CORI one direct question..."
                  className="min-h-[88px] w-full resize-none border-0 bg-white px-4 py-4 text-base outline-none placeholder:text-slate-400 sm:px-5 sm:py-5"
                />
                <div className="border-t bg-white/95 px-3 py-3 backdrop-blur sm:px-4">
                  <div className="flex flex-wrap items-center justify-between gap-3">
                    <div className="flex flex-wrap items-center gap-2 md:gap-2">
                      <button type="button" title="Saved prompts" aria-label="Saved prompts" onClick={() => setUtilityTray((current) => current === "favorites" ? null : "favorites")} className={`inline-flex h-9 w-9 items-center justify-center rounded-full border text-sm transition sm:h-10 sm:w-10 ${utilityTray === "favorites" ? "bg-slate-950 text-white" : "bg-white text-slate-700 hover:bg-slate-50"}`}><FavoritesIcon /></button>
                      <button type="button" title="Conversation history" aria-label="Conversation history" onClick={() => setUtilityTray((current) => current === "history" ? null : "history")} className={`inline-flex h-9 w-9 items-center justify-center rounded-full border text-sm transition sm:h-10 sm:w-10 ${utilityTray === "history" ? "bg-slate-950 text-white" : "bg-white text-slate-700 hover:bg-slate-50"}`}><HistoryIcon /></button>
                      <button type="button" title="Attachment review" aria-label="Attachment review" onClick={() => setUtilityTray((current) => current === "document" ? null : "document")} className={`inline-flex h-9 w-9 items-center justify-center rounded-full border text-sm transition sm:h-10 sm:w-10 ${utilityTray === "document" ? "bg-slate-950 text-white" : "bg-white text-slate-700 hover:bg-slate-50"}`}><AttachmentIcon /></button>
                      <button type="button" title="Context and help" aria-label="Context and help" onClick={() => setUtilityTray((current) => current === "help" ? null : "help")} className={`inline-flex h-9 w-9 items-center justify-center rounded-full border text-sm transition sm:h-10 sm:w-10 ${utilityTray === "help" ? "bg-slate-950 text-white" : "bg-white text-slate-700 hover:bg-slate-50"}`}><HelpIcon /></button>
                      <button type="button" title="Save current prompt" aria-label="Save current prompt" onClick={saveCurrentPrompt} className="inline-flex h-9 w-9 items-center justify-center rounded-full border bg-white text-sm text-slate-700 transition hover:bg-slate-50 sm:h-10 sm:w-10"><SaveIcon /></button>
                      <button type="button" title="Clear conversation" aria-label="Clear conversation" onClick={clearConversation} className="inline-flex h-9 w-9 items-center justify-center rounded-full border bg-white text-sm text-slate-700 transition hover:bg-slate-50 sm:h-10 sm:w-10"><ClearIcon /></button>
                    </div>
                    <button type="submit" className="w-full rounded-full bg-slate-950 px-5 py-2.5 text-sm font-medium text-white hover:bg-black sm:w-auto">Send</button>
                  </div>
                  <div className="mt-3 flex flex-col gap-2 text-[11px] text-slate-500 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between">
                    <div className="flex flex-wrap items-center gap-2">
                      {lastUploadedFileName ? (
                        <button
                          type="button"
                          onClick={() => setUtilityTray("document")}
                          className="rounded-full border bg-slate-50 px-3 py-1.5 font-medium text-slate-600 hover:bg-slate-100"
                        >
                          Attached: {lastUploadedFileName}
                        </button>
                      ) : (
                        <span>Attach a rate confirmation, BOL, POD, or invoice only when you want CORI to review it.</span>
                      )}
                    </div>
                    <div className="flex items-center gap-2">
                      <span className={creditTone}>{creditsRemaining} credits left</span>
                      <button type="button" className="font-medium text-slate-500 hover:text-slate-900">Add credits</button>
                    </div>
                  </div>
                </div>
              </div>
            </form>

            {utilityTray ? (
              <div className="mx-auto mt-4 max-w-3xl rounded-[24px] border bg-white p-4 shadow-sm">
                {utilityTray === "favorites" ? (
                  <div className="space-y-3">
                    <div className="flex items-center justify-between gap-3">
                      <div>
                        <div className="text-sm font-semibold text-slate-900">Saved prompts</div>
                        <div className="text-xs text-slate-500">Insert, manage, or trim the prompts you want close at hand.</div>
                      </div>
                      <div className="text-xs text-slate-400">{favoritePrompts.length}/12 saved</div>
                    </div>
                    <div className="space-y-2">
                      {favoritePrompts.length ? favoritePrompts.map((prompt) => (
                        <div key={prompt} className="flex items-center justify-between gap-3 rounded-2xl border bg-slate-50 px-3 py-3">
                          <button type="button" onClick={() => insertPrompt(prompt)} className="text-left text-sm font-medium text-slate-700 hover:text-slate-950">
                            {prompt}
                          </button>
                          <button type="button" onClick={() => removeFavorite(prompt)} className="rounded-full border bg-white px-2.5 py-1 text-[11px] font-medium text-slate-600 hover:bg-slate-100">Remove</button>
                        </div>
                      )) : <div className="text-xs text-slate-500">No saved prompts yet.</div>}
                    </div>
                  </div>
                ) : null}

                {utilityTray === "history" ? (
                  <div className="space-y-3">
                    <div className="flex items-center justify-between gap-3">
                      <div>
                        <div className="text-sm font-semibold text-slate-900">Conversation history</div>
                        <div className="text-xs text-slate-500">Restore a recent CORI thread without cluttering the main chat surface.</div>
                      </div>
                    </div>
                    <div className="space-y-2">
                      {conversationHistory.length ? conversationHistory.map((conversation) => (
                        <div key={conversation.id} className="flex items-center justify-between gap-3 rounded-2xl border bg-slate-50 px-3 py-3">
                          <button type="button" onClick={() => restoreConversation(conversation)} className="min-w-0 text-left">
                            <div className="truncate text-sm font-medium text-slate-800">{conversation.title}</div>
                            <div className="mt-1 text-xs text-slate-500">{new Date(conversation.updatedAt).toLocaleString()}</div>
                          </button>
                          <button type="button" onClick={() => removeHistoryConversation(conversation.id)} className="rounded-full border bg-white px-2.5 py-1 text-[11px] font-medium text-slate-600 hover:bg-slate-100">Remove</button>
                        </div>
                      )) : <div className="text-xs text-slate-500">No saved conversations yet.</div>}
                    </div>
                    {recentPrompts.length ? (
                      <div className="border-t pt-3">
                        <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Recent prompts</div>
                        <div className="mt-2 flex flex-wrap gap-2">
                          {recentPrompts.map((prompt) => (
                            <button key={prompt} type="button" onClick={() => insertPrompt(prompt)} className="rounded-full border bg-slate-50 px-3 py-2 text-xs font-medium text-slate-700 hover:bg-slate-100">
                              {prompt}
                            </button>
                          ))}
                        </div>
                      </div>
                    ) : null}
                  </div>
                ) : null}

                {utilityTray === "help" ? (
                  <div className="grid gap-4 md:grid-cols-2">
                    <div className="space-y-2">
                      <div className="text-sm font-semibold text-slate-900">Focused help</div>
                      <div className="text-sm text-slate-600">Users do not need visible prompt clutter. Ask one direct question about the job in front of you and CORI will respond with the risk and next step.</div>
                      {source ? <div className="rounded-2xl bg-slate-50 px-3 py-3 text-xs text-slate-600">Opened from <span className="font-medium text-slate-900">{source.replaceAll("-", " ")}</span>.</div> : null}
                      {(contextTitle || contextDetail) ? <div className="rounded-2xl border bg-slate-50 px-3 py-3 text-xs text-slate-600"><span className="font-medium text-slate-900">Current context:</span> {contextTitle ?? contextDetail}</div> : null}
                    </div>
                    <div className="space-y-3">
                      <div className="text-sm font-semibold text-slate-900">Quick inserts</div>
                      <div className="flex flex-wrap gap-2">
                        {supportPrompts.length ? supportPrompts.map((prompt) => (
                          <button key={prompt} type="button" onClick={() => insertPrompt(prompt)} className="rounded-full border bg-slate-50 px-3 py-2 text-xs font-medium text-slate-700 hover:bg-slate-100">
                            {prompt}
                          </button>
                        )) : <div className="text-xs text-slate-500">No contextual inserts are needed right now.</div>}
                      </div>
                    </div>
                  </div>
                ) : null}

                {utilityTray === "document" ? (
                  <div className="space-y-4">
                    <div className="flex flex-wrap items-start justify-between gap-3">
                      <div>
                        <div className="text-sm font-semibold text-slate-900">Attachment review</div>
                        <div className="text-xs text-slate-500">Keep the chat clean until you need document help. Upload a rate confirmation, BOL, POD, or invoice and CORI will prepare a supervised next-step suggestion.</div>
                      </div>
                      <label className="inline-flex cursor-pointer rounded-full bg-slate-950 px-4 py-2 text-xs font-medium text-white hover:bg-black">
                        Choose file
                        <input type="file" className="hidden" onChange={handleFilePickerChange} />
                      </label>
                    </div>

                    <div className="grid gap-3 lg:grid-cols-[1.2fr_0.8fr]">
                      <div className="rounded-2xl border bg-slate-50 p-4">
                        <div className="flex flex-wrap items-center justify-between gap-3">
                          <div>
                            <div className="text-[11px] font-semibold uppercase tracking-wide text-slate-500">Current attachment</div>
                            <div className="mt-1 text-sm font-medium text-slate-900">{lastUploadedFileName ?? "No file selected yet"}</div>
                          </div>
                          {uploadedDocument ? <div className="rounded-full border bg-white px-3 py-1 text-[11px] font-medium text-slate-600">{uploadedDocument.documentType}</div> : null}
                        </div>
                        <div className="mt-3 rounded-2xl bg-white px-3 py-3 text-xs text-slate-700">{uploadStatus}</div>
                        {uploadedDocument ? (
                          <div className="mt-3 grid gap-2 sm:grid-cols-2">
                            <div className="rounded-2xl bg-white px-3 py-3 text-xs text-slate-700"><span className="font-medium text-slate-900">Load ref:</span> {uploadedDocument.extracted.loadRef ?? "Not found yet"}</div>
                            <div className="rounded-2xl bg-white px-3 py-3 text-xs text-slate-700"><span className="font-medium text-slate-900">Rate:</span> {uploadedDocument.extracted.rate ?? "Not found yet"}</div>
                            <div className="rounded-2xl bg-white px-3 py-3 text-xs text-slate-700"><span className="font-medium text-slate-900">Pickup:</span> {uploadedDocument.extracted.pickup ?? "Not found yet"}</div>
                            <div className="rounded-2xl bg-white px-3 py-3 text-xs text-slate-700"><span className="font-medium text-slate-900">Delivery:</span> {uploadedDocument.extracted.delivery ?? "Not found yet"}</div>
                            <div className="rounded-2xl bg-white px-3 py-3 text-xs text-slate-700"><span className="font-medium text-slate-900">Truck:</span> {uploadedDocument.extracted.truck ?? "Not found yet"}</div>
                            <div className="rounded-2xl bg-white px-3 py-3 text-xs text-slate-700"><span className="font-medium text-slate-900">Driver:</span> {uploadedDocument.extracted.driver ?? "Not found yet"}</div>
                          </div>
                        ) : null}
                      </div>

                      <div className="rounded-2xl border bg-slate-50 p-4 text-xs text-slate-700">
                        <div className="text-[11px] font-semibold uppercase tracking-wide text-slate-500">CORI review</div>
                        {uploadedDocument ? (
                          <div className="mt-3 space-y-3">
                            <div className="rounded-2xl bg-white px-3 py-3"><span className="font-medium text-slate-900">Next step:</span> {uploadedDocument.suggestedAction}</div>
                            <div className="rounded-2xl bg-white px-3 py-3"><span className="font-medium text-slate-900">Suggested stage:</span> {uploadedDocument.suggestedStage}</div>
                            <div className="rounded-2xl bg-white px-3 py-3"><span className="font-medium text-slate-900">Match status:</span> {matchStatus}</div>
                            <div className="rounded-2xl bg-white px-3 py-3">{formatLoadContext(matchingLoad)}</div>
                            {matchingLoad && getSuggestedStatus(uploadedDocument.documentType) ? (
                              <button
                                type="button"
                                onClick={applySuggestedStageUpdate}
                                disabled={isApplyingStageUpdate}
                                className="w-full rounded-full bg-slate-950 px-4 py-2 text-xs font-medium text-white hover:bg-black disabled:opacity-60"
                              >
                                {isApplyingStageUpdate ? "Applying..." : `Approve move to ${getStatusLabel(getSuggestedStatus(uploadedDocument.documentType))}`}
                              </button>
                            ) : null}
                            {stageActionStatus ? <div className="rounded-2xl bg-white px-3 py-3 text-[11px] text-slate-600">{stageActionStatus}</div> : null}
                          </div>
                        ) : (
                          <div className="mt-3 rounded-2xl bg-white px-3 py-3 text-xs text-slate-600">No attachment is in review yet. Upload a document only when you want CORI to prepare a suggested next step.</div>
                        )}
                      </div>
                    </div>
                  </div>
                ) : null}
              </div>
            ) : null}
          </div>
        </section>
      </div>
      </div>
    </PlanFeatureGate>
  );
}
