"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { CallCopilotShell } from "@/components/cori/call-copilot-shell";
import type { CallCopilotLaunchContext } from "@/components/cori/call-copilot-support";

type PopupMode = "ask" | "call";

type PageContext = {
  title: string;
  detail: string;
  smartPrompt: string;
};

const PAGE_CONTEXT: Array<{ match: RegExp; context: PageContext }> = [
  { match: /^\/dispatch/, context: { title: "Dispatch Board", detail: "Live load movement and the next dispatcher action.", smartPrompt: "What should I handle first on this dispatch board?" } },
  { match: /^\/loads/, context: { title: "Loads", detail: "Load records, status updates, and corrections.", smartPrompt: "What is the next load step I should handle?" } },
  { match: /^\/billing/, context: { title: "Billing Records", detail: "Invoices, unpaid loads, and payment follow-up.", smartPrompt: "What payment follow-up should I handle first?" } },
  { match: /^\/documents/, context: { title: "Paperwork", detail: "Missing proof, PODs, BOLs, and files to link.", smartPrompt: "What missing paperwork should I handle first?" } },
  { match: /^\/routes/, context: { title: "Routes", detail: "Load, truck, driver, weather, stops, and driver briefing.", smartPrompt: "Help me check this route before the driver goes." } },
  { match: /^\/fleet-map/, context: { title: "Fleet Map", detail: "Live GPS and estimated truck positions for dispatched trucks.", smartPrompt: "Which truck on this map needs attention first?" } },
  { match: /^\/crm|^\/brokers|^\/shippers|^\/companies/, context: { title: "CRM", detail: "Companies, brokers, shippers, and follow-up timing.", smartPrompt: "What relationship follow-up should I handle next?" } },
  { match: /^\/owner-operators|^\/drivers/, context: { title: "People & Assets", detail: "Driver and owner-operator records, trucks, and follow-up.", smartPrompt: "What people or asset follow-up should I handle next?" } },
  { match: /^\/dashboard/, context: { title: "CORI Briefing", detail: "Today’s business read and clear next steps.", smartPrompt: "What should I focus on first from today’s briefing?" } },
  { match: /^\/trucks/, context: { title: "Truck workspace", detail: "Truck dashboard, next-load status, and truck-first actions.", smartPrompt: "What truck action should I handle first from this truck page?" } },
];

function getPageContext(pathname: string): PageContext | null {
  return PAGE_CONTEXT.find((entry) => entry.match.test(pathname))?.context ?? null;
}

function generateCoriReply(prompt: string) {
  const text = prompt.trim().toLowerCase();
  if (text.includes("next") && text.includes("truck")) return "Start with the truck most likely to lose revenue if you wait any longer.";
  if (text.includes("billing")) return "Confirm what is due, what document is still missing, and what one follow-up will move the money fastest.";
  if (text.includes("document")) return "Find the issue, tie it to the right load or truck, and clear the missing paperwork before it slows the work down.";
  return "Keep the question simple. CORI is best when you ask for the next move, the biggest risk, or the clearest one-step answer.";
}

export function CoriGlobalPopup() {
  const pathname = usePathname();
  if (pathname.startsWith("/cori")) return null;

  const pageContext = useMemo(() => getPageContext(pathname), [pathname]);
  const [isOpen, setIsOpen] = useState(false);
  const [mode, setMode] = useState<PopupMode>("ask");
  const [input, setInput] = useState("");
  const [answer, setAnswer] = useState("");
  const [callLaunchContext, setCallLaunchContext] = useState<CallCopilotLaunchContext | undefined>(undefined);

  function openMode(nextMode: PopupMode) {
    setMode(nextMode);
    if (nextMode !== "call") setCallLaunchContext(undefined);
    setIsOpen(true);
  }


  useEffect(() => {
    function handleOpenCallCopilot(event: Event) {
      const customEvent = event as CustomEvent<CallCopilotLaunchContext | undefined>;
      setCallLaunchContext(customEvent.detail ?? undefined);
      setMode("call");
      setIsOpen(true);
    }

    window.addEventListener("dispatchspot:open-call-copilot", handleOpenCallCopilot as EventListener);
    return () => window.removeEventListener("dispatchspot:open-call-copilot", handleOpenCallCopilot as EventListener);
  }, []);

  function sendAskPrompt(prompt?: string) {
    const value = (prompt ?? input).trim();
    if (!value) return;
    setAnswer(generateCoriReply(value));
    if (!prompt) setInput("");
  }

  return (
    <>
      <div className="fixed bottom-5 right-5 z-40 flex items-center gap-2">
        <button
          type="button"
          onClick={() => openMode("ask")}
          className="inline-flex items-center gap-2 rounded-full border border-sky-200 bg-white px-4 py-3 text-sm font-semibold text-sky-700 shadow-lg shadow-slate-300/40 transition hover:-translate-y-0.5 hover:bg-sky-50"
        >
          <span>Ask</span>
        </button>
        <button
          type="button"
          onClick={() => openMode("call")}
          className="inline-flex items-center gap-2 rounded-full border border-emerald-200 bg-white px-4 py-3 text-sm font-semibold text-emerald-700 shadow-lg shadow-slate-300/40 transition hover:-translate-y-0.5 hover:bg-emerald-50"
        >
          <span>Call help</span>
        </button>
      </div>

      {isOpen ? (
        <div className="fixed inset-0 z-50 flex items-end justify-end bg-slate-950/25 p-3 sm:p-5">
          <div className={`flex ${mode === "call" ? "h-[88vh] max-w-5xl" : "h-[82vh] max-w-md"} w-full flex-col overflow-hidden rounded-[28px] border border-slate-200 bg-white shadow-2xl`}>
            <div className="flex items-center justify-between border-b border-slate-200 px-4 py-3">
              <div>
                <div className="text-sm font-semibold text-slate-900">{mode === "ask" ? "Ask CORI" : "CORI Live Call Copilot"}</div>
                <div className="text-xs text-slate-500">{pageContext ? `${pageContext.title} · ${pageContext.detail}` : "Quick help from anywhere in the workspace."}</div>
              </div>
              <div className="flex items-center gap-2">
                <button type="button" onClick={() => setMode("ask")} className={`rounded-full px-3 py-1.5 text-xs font-medium ${mode === "ask" ? "bg-sky-100 text-sky-700" : "bg-slate-100 text-slate-600"}`}>Ask</button>
                <button type="button" onClick={() => setMode("call")} className={`rounded-full px-3 py-1.5 text-xs font-medium ${mode === "call" ? "bg-emerald-100 text-emerald-700" : "bg-slate-100 text-slate-600"}`}>Call</button>
                <Link href={mode === "ask" ? "/cori" : "/cori/quotes"} className="text-xs font-medium text-sky-700 hover:text-sky-800">Open full page</Link>
                <button type="button" onClick={() => setIsOpen(false)} className="rounded-full p-2 text-slate-500 hover:bg-slate-100 hover:text-slate-700">✕</button>
              </div>
            </div>

            {mode === "ask" ? (
              <>
                <div className="flex-1 overflow-y-auto bg-slate-50 px-4 py-4">
                  <div className="rounded-3xl border border-dashed border-slate-200 bg-white px-5 py-6 shadow-sm">
                    <div className="text-sm font-semibold text-slate-900">{pageContext ? `Ask CORI about ${pageContext.title.toLowerCase()}.` : "Ask CORI what to do next."}</div>
                    <div className="mt-2 text-xs text-slate-500">{pageContext ? pageContext.smartPrompt : "Keep it simple and ask for the next move."}</div>
                    {pageContext ? (
                      <button type="button" onClick={() => sendAskPrompt(pageContext.smartPrompt)} className="mt-4 rounded-full border border-sky-200 bg-sky-50 px-4 py-2 text-sm font-medium text-sky-700 hover:bg-sky-100">Ask about this page</button>
                    ) : null}
                  </div>
                  {answer ? (
                    <div className="mt-4 rounded-3xl border border-slate-200 bg-white px-4 py-4 shadow-sm">
                      <div className="text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-400">CORI</div>
                      <div className="mt-2 text-sm leading-6 text-slate-700">{answer}</div>
                    </div>
                  ) : null}
                </div>
                <div className="border-t border-slate-200 bg-white p-4">
                  <div className="rounded-[24px] border border-slate-200 bg-slate-50 p-3 shadow-sm">
                    <textarea
                      value={input}
                      onChange={(event) => setInput(event.target.value)}
                      placeholder="Ask CORI one direct question..."
                      rows={3}
                      className="min-h-[72px] w-full resize-none bg-transparent text-sm text-slate-800 outline-none placeholder:text-slate-400"
                    />
                    <div className="mt-3 flex items-center justify-end">
                      <button type="button" onClick={() => sendAskPrompt()} className="inline-flex items-center justify-center rounded-full bg-sky-600 px-4 py-2 text-sm font-semibold text-white hover:bg-sky-700">Send</button>
                    </div>
                  </div>
                </div>
              </>
            ) : (
              <div className="flex-1 overflow-y-auto bg-slate-50 p-4">
                <CallCopilotShell variant="popup" launchContext={callLaunchContext} onClose={() => setIsOpen(false)} />
              </div>
            )}
          </div>
        </div>
      ) : null}
    </>
  );
}
