"use client";
/**
 * Ask AI — floating glass assistant available on every app page. Text chat plus voice (browser speech recognition in,
 * speech synthesis out). It can explain the product and do work (create leads/tasks, pull numbers, open pages);
 * outbound or hard-to-undo actions come back as confirmation cards the user must approve.
 * Open it from anywhere with window.dispatchEvent(new CustomEvent("assistant:open")) or Ctrl/⌘ + J.
 */
import { useCallback, useEffect, useRef, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import Link from "next/link";
import { ArrowRight, Check, Lock, Mic, MicOff, RotateCcw, Send, Sparkles, Volume2, VolumeX, X } from "lucide-react";
import { ClientApiError, api, cx } from "./ui";

type Action = { type: "navigate"; href: string; label: string } | { type: "confirm"; token: string; title: string; detail: string };
type Msg = { role: "user" | "assistant"; content: string; actions?: Action[]; error?: boolean };
type ConfirmState = Record<string, "pending" | "done" | "cancelled" | "failed">;

const SUGGESTIONS = ["How am I doing this month?", "Show my tasks due today", "Add a lead: Rahim, 01711000000", "Which conversations need a reply?", "How do I import contacts?", "Turn on two-factor authentication"];
const STORE = "tp-assistant";

/* minimal typing for the Web Speech API (not in lib.dom for all browsers) */
type Rec = { lang: string; interimResults: boolean; continuous: boolean; start(): void; stop(): void; abort(): void; onresult: ((e: any) => void) | null; onend: (() => void) | null; onerror: ((e: any) => void) | null };
const speechCtor = (): (new () => Rec) | null => (typeof window === "undefined" ? null : ((window as any).SpeechRecognition ?? (window as any).webkitSpeechRecognition ?? null));

export function Assistant({ voice }: { voice: boolean }) {
  const [open, setOpen] = useState(false);
  const [msgs, setMsgs] = useState<Msg[]>([]);
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const [listening, setListening] = useState(false);
  const [interim, setInterim] = useState("");
  const [speak, setSpeak] = useState(true);
  const [lang, setLang] = useState<"en-US" | "bn-BD">("en-US");
  const [confirms, setConfirms] = useState<ConfirmState>({});
  const [voiceSupported, setVoiceSupported] = useState(false);
  const recRef = useRef<Rec | null>(null);
  const endRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const router = useRouter();
  const pathname = usePathname();

  // restore the conversation for this tab
  useEffect(() => {
    setVoiceSupported(!!speechCtor());
    try { const s = sessionStorage.getItem(STORE); if (s) setMsgs(JSON.parse(s)); } catch {}
  }, []);
  useEffect(() => { try { sessionStorage.setItem(STORE, JSON.stringify(msgs.slice(-30))); } catch {} }, [msgs]);
  useEffect(() => { endRef.current?.scrollIntoView({ behavior: "smooth", block: "end" }); }, [msgs, busy, interim]);

  useEffect(() => {
    const onOpen = (e: Event) => { setOpen(true); if ((e as CustomEvent).detail?.voice) setTimeout(() => startListening(), 150); else setTimeout(() => inputRef.current?.focus(), 120); };
    const onKey = (e: KeyboardEvent) => { if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "j") { e.preventDefault(); setOpen((o) => !o); } if (e.key === "Escape") setOpen(false); };
    window.addEventListener("assistant:open", onOpen);
    window.addEventListener("keydown", onKey);
    return () => { window.removeEventListener("assistant:open", onOpen); window.removeEventListener("keydown", onKey); };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const say = useCallback((text: string) => {
    if (!speak || typeof window === "undefined" || !("speechSynthesis" in window)) return;
    window.speechSynthesis.cancel();
    const u = new SpeechSynthesisUtterance(text.replace(/[*_#`>]/g, "").slice(0, 600));
    u.lang = lang;
    const v = window.speechSynthesis.getVoices().find((x) => x.lang.toLowerCase().startsWith(lang.slice(0, 2)));
    if (v) u.voice = v;
    u.rate = 1.02;
    window.speechSynthesis.speak(u);
  }, [speak, lang]);

  const send = useCallback(async (text: string, viaVoice = false) => {
    const t = text.trim();
    if (!t || busy) return;
    const next: Msg[] = [...msgs, { role: "user", content: t }];
    setMsgs(next);
    setInput("");
    setBusy(true);
    try {
      const history = next.filter((m) => !m.error).map((m) => ({ role: m.role, content: m.content.slice(0, 6000) })).slice(-20);
      const r = await api<{ data: { reply: string; actions: Action[]; source: string } }>("/ai/assistant", { body: { messages: history, page: pathname, voice: viaVoice || undefined } });
      setMsgs((m) => [...m, { role: "assistant", content: r.data.reply, actions: r.data.actions }]);
      if (viaVoice) say(r.data.reply);
    } catch (e) {
      const err = e as ClientApiError;
      const msg = err.code === "plan_upgrade_required" ? `${err.message}. You can still type your question.` : err.code === "ai_credits_exhausted" ? "This workspace has used its AI credits for the month. An admin can upgrade in Plan & billing." : err.message || "Something went wrong.";
      setMsgs((m) => [...m, { role: "assistant", content: msg, error: true }]);
    }
    setBusy(false);
  }, [busy, msgs, pathname, say]);

  const startListening = useCallback(() => {
    const Ctor = speechCtor();
    if (!Ctor || !voice) return;
    window.speechSynthesis?.cancel();
    const rec = new Ctor();
    rec.lang = lang;
    rec.interimResults = true;
    rec.continuous = false;
    let finalText = "";
    rec.onresult = (e: any) => {
      let live = "";
      for (let i = e.resultIndex; i < e.results.length; i++) {
        const r = e.results[i];
        if (r.isFinal) finalText += r[0].transcript; else live += r[0].transcript;
      }
      setInterim(finalText + live);
    };
    rec.onerror = () => { setListening(false); setInterim(""); };
    rec.onend = () => { setListening(false); setInterim(""); if (finalText.trim()) void send(finalText, true); };
    recRef.current = rec;
    setListening(true);
    try { rec.start(); } catch { setListening(false); }
  }, [lang, send, voice]);

  const stopListening = () => { recRef.current?.stop(); };

  const confirm = async (token: string) => {
    setConfirms((c) => ({ ...c, [token]: "pending" }));
    try {
      const r = await api<{ data: { done: boolean; detail: string } }>("/ai/assistant/confirm", { body: { token } });
      setConfirms((c) => ({ ...c, [token]: r.data.done ? "done" : "failed" }));
      setMsgs((m) => [...m, { role: "assistant", content: r.data.done ? `✓ ${r.data.detail}` : `That didn't go through: ${r.data.detail}`, error: !r.data.done }]);
      router.refresh();
    } catch (e) {
      setConfirms((c) => ({ ...c, [token]: "failed" }));
      setMsgs((m) => [...m, { role: "assistant", content: (e as Error).message, error: true }]);
    }
  };

  const reset = () => { setMsgs([]); setConfirms({}); window.speechSynthesis?.cancel(); };

  return (
    <>
      {/* launcher */}
      <button onClick={() => setOpen((o) => !o)} aria-label={open ? "Close AI assistant" : "Ask AI"} aria-expanded={open}
        className={cx("group fixed bottom-5 right-5 z-[60] flex h-14 items-center gap-2 rounded-full pl-4 pr-5 text-white shadow-[0_12px_40px_-8px_rgba(37,99,235,.65)] transition-all duration-300 hover:-translate-y-0.5 hover:shadow-[0_18px_50px_-8px_rgba(37,99,235,.8)] print:hidden",
          "bg-[linear-gradient(135deg,#4F8BFF_0%,#2563EB_55%,#1D3FBF_100%)] ring-1 ring-white/40", open && "pointer-events-none scale-90 opacity-0")}>
        <span className="relative grid h-8 w-8 place-items-center rounded-full bg-white/20 backdrop-blur"><Sparkles className="h-4 w-4" /><span className="absolute inset-0 animate-ping rounded-full bg-white/25 [animation-duration:2.6s]" /></span>
        <span className="text-[13.5px] font-semibold">Ask AI</span>
      </button>

      {/* panel */}
      <div role="dialog" aria-label="AI assistant" aria-hidden={!open}
        className={cx("fixed bottom-4 right-4 z-[61] flex w-[min(420px,calc(100vw-2rem))] origin-bottom-right flex-col overflow-hidden rounded-[26px] border border-white/70 bg-white/75 shadow-[0_30px_80px_-20px_rgba(15,23,42,.35)] backdrop-blur-2xl transition-all duration-300 dark:border-white/10 dark:bg-[#0E1A33]/85 print:hidden",
          "h-[min(640px,calc(100dvh-2rem))]", open ? "translate-y-0 scale-100 opacity-100" : "pointer-events-none translate-y-4 scale-95 opacity-0")}>
        {/* header */}
        <div className="relative flex items-center gap-3 overflow-hidden px-4 py-3.5 text-white bg-[linear-gradient(135deg,#4F8BFF_0%,#2563EB_60%,#1D3FBF_100%)]">
          <div className="pointer-events-none absolute -right-10 -top-12 h-36 w-36 rounded-full bg-white/20 blur-2xl" />
          <span className="grid h-9 w-9 place-items-center rounded-[12px] bg-white/20 ring-1 ring-white/40 backdrop-blur"><Sparkles className="h-[18px] w-[18px]" /></span>
          <div className="min-w-0 flex-1">
            <div className="font-display text-[15px] font-bold leading-tight">AI assistant</div>
            <div className="text-[11.5px] text-white/80">{listening ? "Listening…" : busy ? "Working on it…" : "Ask anything or tell me what to do"}</div>
          </div>
          {voice && voiceSupported && (
            <>
              <button onClick={() => setLang((l) => (l === "en-US" ? "bn-BD" : "en-US"))} className="rounded-full bg-white/15 px-2.5 py-1 text-[11px] font-semibold hover:bg-white/25" aria-label="Voice language">{lang === "en-US" ? "EN" : "বাংলা"}</button>
              <button onClick={() => { setSpeak((s) => !s); window.speechSynthesis?.cancel(); }} className="rounded-full p-1.5 hover:bg-white/20" aria-label={speak ? "Mute spoken replies" : "Speak replies"}>{speak ? <Volume2 className="h-4 w-4" /> : <VolumeX className="h-4 w-4" />}</button>
            </>
          )}
          {!!msgs.length && <button onClick={reset} className="rounded-full p-1.5 hover:bg-white/20" aria-label="New conversation"><RotateCcw className="h-4 w-4" /></button>}
          <button onClick={() => setOpen(false)} className="rounded-full p-1.5 hover:bg-white/20" aria-label="Close"><X className="h-4 w-4" /></button>
        </div>

        {/* messages */}
        <div className="no-scrollbar flex-1 space-y-3 overflow-y-auto px-4 py-4">
          {!msgs.length && (
            <div className="space-y-4">
              <div className="rounded-[18px] border border-white/80 bg-white/70 p-4 text-[13px] leading-relaxed text-ink-2 shadow-sm dark:border-white/10 dark:bg-white/5">
                <div className="mb-1 font-display text-[14px] font-bold text-ink">Hi! I can help you work faster.</div>
                Ask how anything works, or tell me to add a lead, create a task, check your numbers, or draft a message. I always ask before sending anything.
              </div>
              <div className="flex flex-wrap gap-2">
                {SUGGESTIONS.map((s) => <button key={s} onClick={() => send(s)} className="rounded-full border border-brand/20 bg-brand/5 px-3 py-1.5 text-[12px] font-medium text-brand transition hover:-translate-y-px hover:bg-brand/10">{s}</button>)}
              </div>
              {!voice && (
                <Link href="/settings/billing?upgrade=voice_ai" className="flex items-center gap-2 rounded-[14px] border border-dashed border-line px-3 py-2.5 text-[12px] text-ink-2 hover:border-brand/40 hover:text-brand">
                  <Lock className="h-3.5 w-3.5" /> Voice chat is included from the Growth plan. <span className="ml-auto font-semibold">Upgrade</span>
                </Link>
              )}
            </div>
          )}
          {msgs.map((m, i) => (
            <div key={i} className={cx("flex", m.role === "user" ? "justify-end" : "justify-start")}>
              <div className={cx("max-w-[86%] space-y-2")}>
                <div className={cx("whitespace-pre-wrap rounded-[18px] px-3.5 py-2.5 text-[13px] leading-relaxed",
                  m.role === "user" ? "rounded-br-[6px] bg-[linear-gradient(135deg,#3B7BFF,#2563EB)] text-white shadow-[0_8px_20px_-10px_rgba(37,99,235,.8)]"
                    : m.error ? "rounded-bl-[6px] border border-red-200 bg-red-50/80 text-red-700 dark:border-red-500/30 dark:bg-red-500/10 dark:text-red-300"
                    : "rounded-bl-[6px] border border-white/80 bg-white/80 text-ink shadow-sm dark:border-white/10 dark:bg-white/[.06]")}>{m.content}</div>
                {m.actions?.map((a, j) => a.type === "navigate" ? (
                  <button key={j} onClick={() => router.push(a.href)} className="flex items-center gap-1.5 rounded-full border border-brand/25 bg-white/80 px-3 py-1.5 text-[12px] font-semibold text-brand hover:bg-brand/5 dark:bg-white/5">{a.label}<ArrowRight className="h-3.5 w-3.5" /></button>
                ) : (
                  <div key={j} className="rounded-[16px] border border-amber-200 bg-amber-50/80 p-3 text-[12.5px] dark:border-amber-400/30 dark:bg-amber-400/10">
                    <div className="font-semibold text-ink">{a.title}</div>
                    <div className="mt-1 line-clamp-5 whitespace-pre-wrap text-ink-2">{a.detail}</div>
                    {confirms[a.token] === "done" ? <div className="mt-2 flex items-center gap-1 font-semibold text-green-700 dark:text-green-400"><Check className="h-3.5 w-3.5" />Done</div>
                      : confirms[a.token] === "cancelled" ? <div className="mt-2 text-ink-3">Cancelled</div>
                      : (
                        <div className="mt-2.5 flex gap-2">
                          <button disabled={confirms[a.token] === "pending"} onClick={() => confirm(a.token)} className="rounded-full bg-brand px-3.5 py-1.5 text-[12px] font-semibold text-white shadow hover:bg-brand/90 disabled:opacity-60">{confirms[a.token] === "pending" ? "Working…" : confirms[a.token] === "failed" ? "Try again" : "Confirm"}</button>
                          <button onClick={() => setConfirms((c) => ({ ...c, [a.token]: "cancelled" }))} className="rounded-full px-3 py-1.5 text-[12px] font-medium text-ink-2 hover:bg-black/5 dark:hover:bg-white/10">Cancel</button>
                        </div>
                      )}
                  </div>
                ))}
              </div>
            </div>
          ))}
          {busy && <div className="flex gap-1.5 px-1 py-2" aria-label="Thinking">{[0, 1, 2].map((d) => <span key={d} className="h-2 w-2 animate-bounce rounded-full bg-brand/60" style={{ animationDelay: `${d * 140}ms` }} />)}</div>}
          {listening && <div className="rounded-[16px] border border-brand/20 bg-brand/5 px-3.5 py-2.5 text-[13px] italic text-brand">{interim || "Speak now…"}</div>}
          <div ref={endRef} />
        </div>

        {/* composer */}
        <form onSubmit={(e) => { e.preventDefault(); void send(input); }} className="border-t border-white/60 bg-white/50 p-3 dark:border-white/10 dark:bg-white/[.03]">
          <div className="flex items-end gap-2 rounded-[18px] border border-white/80 bg-white/90 p-1.5 pl-3 shadow-sm focus-within:border-brand/40 focus-within:ring-4 focus-within:ring-brand/10 dark:border-white/10 dark:bg-white/5">
            <textarea ref={inputRef} rows={1} value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void send(input); } }}
              placeholder={listening ? "Listening…" : "Ask or tell me what to do…"} aria-label="Message the AI assistant" className="max-h-28 min-h-[36px] flex-1 resize-none bg-transparent py-2 text-[13.5px] outline-none placeholder:text-ink-3" />
            {voiceSupported && (voice ? (
              <button type="button" onClick={listening ? stopListening : startListening} aria-label={listening ? "Stop listening" : "Speak to the assistant"}
                className={cx("relative grid h-9 w-9 shrink-0 place-items-center rounded-full transition", listening ? "bg-red-500 text-white" : "text-ink-2 hover:bg-brand/10 hover:text-brand")}>
                {listening && <span className="absolute inset-0 animate-ping rounded-full bg-red-400/50" />}
                {listening ? <MicOff className="relative h-4 w-4" /> : <Mic className="h-4 w-4" />}
              </button>
            ) : (
              <Link href="/settings/billing?upgrade=voice_ai" aria-label="Voice chat needs the Growth plan" title="Voice chat needs the Growth plan" className="relative grid h-9 w-9 shrink-0 place-items-center rounded-full text-ink-3 hover:text-brand"><Mic className="h-4 w-4" /><Lock className="absolute bottom-1.5 right-1.5 h-2.5 w-2.5" /></Link>
            ))}
            <button type="submit" disabled={!input.trim() || busy} aria-label="Send" className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-[linear-gradient(135deg,#4F8BFF,#2563EB)] text-white shadow-[0_6px_16px_-6px_rgba(37,99,235,.8)] transition hover:scale-105 disabled:opacity-40 disabled:hover:scale-100"><Send className="h-4 w-4" /></button>
          </div>
          <div className="mt-1.5 px-1 text-center text-[10.5px] text-ink-3">AI can make mistakes — check important details. Ctrl/⌘ + J to toggle.</div>
        </form>
      </div>
    </>
  );
}
