"use client";

import { useEffect, useRef, useState } from "react";
import { useSdk } from "@lynkd/messaging-inbox-sdk";
import { useUi } from "@/lib/ui-state";
import { Sparkles, X, Copy, Send, RefreshCw, MessageSquareReply, FileText, WandSparkles, Languages } from "lucide-react";

interface Turn {
  role: "user" | "ai";
  text: string;
  error?: boolean;
}

const QUICK = [
  { label: "Summarize message", icon: FileText, prompt: "Summarize the message above in one or two sentences." },
  { label: "What should I reply?", icon: MessageSquareReply, prompt: "Suggest a thoughtful reply to the message above. Write it in first person, ready to send." },
  { label: "Improve my writing", icon: WandSparkles, prompt: "Rewrite the message above to be clearer and more professional, keeping the meaning." },
  { label: "Explain simply", icon: Languages, prompt: "Explain the message above in simple, plain language." },
];

export function AiPanel() {
  const { aiPanel, closeAi, toast } = useUi();
  const { client } = useSdk();
  const [context, setContext] = useState<string>("");
  const [turns, setTurns] = useState<Turn[]>([]);
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);

  // seed from the message that opened the panel
  useEffect(() => {
    if (!aiPanel) return;
    setContext(aiPanel.context ?? "");
    setTurns([]);
    setInput("");
    if (aiPanel.prompt) void ask(aiPanel.prompt, aiPanel.context ?? "");
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [aiPanel]);

  useEffect(() => {
    scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
  }, [turns, busy]);

  if (!aiPanel) return null;

  async function ask(prompt: string, ctx: string) {
    const p = prompt.trim();
    if (!p || busy) return;
    setInput("");
    setTurns((t) => [...t, { role: "user", text: p }]);
    setBusy(true);
    try {
      const res = await client.ai(p, ctx || undefined);
      if (res.ok && res.text) {
        setTurns((t) => [...t, { role: "ai", text: res.text as string }]);
      } else {
        setTurns((t) => [...t, { role: "ai", text: res.error || "The AI couldn't respond.", error: true }]);
      }
    } catch (e) {
      setTurns((t) => [...t, { role: "ai", text: `Request failed: ${(e as Error).message}`, error: true }]);
    } finally {
      setBusy(false);
    }
  }

  const copy = async (text: string) => {
    try { await navigator.clipboard?.writeText(text); toast("Copied to clipboard", "success"); }
    catch { toast("Couldn't access the clipboard", "danger"); }
  };

  return (
    <div className="fixed inset-0 z-40 flex justify-end bg-black/40 animate-fade-in" onClick={closeAi}>
      <div role="dialog" aria-modal="true" aria-label="AI assistant" className="flex h-full w-[min(420px,100vw)] flex-col border-l border-border bg-surface shadow-pop" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-border px-4 py-3">
          <div className="flex items-center gap-2">
            <span className="grid h-7 w-7 place-items-center rounded-control bg-accent-soft text-accent"><Sparkles size={16} /></span>
            <div>
              <div className="text-[14px] font-bold leading-none">AI Assistant</div>
              <div className="text-[11px] text-dim">Powered by Gemini</div>
            </div>
          </div>
          <button onClick={closeAi} className="text-muted hover:text-ink"><X size={18} /></button>
        </div>

        <div ref={scrollRef} className="min-h-0 flex-1 space-y-3 overflow-y-auto p-4">
          {context && (
            <div className="rounded-control border border-border bg-panel p-3">
              <div className="mb-1 text-[11px] font-bold uppercase tracking-wide text-dim">Message context</div>
              <div className="max-h-32 overflow-y-auto whitespace-pre-wrap text-[13px] text-ink/80">{context}</div>
            </div>
          )}

          {turns.length === 0 && !busy && (
            <div className="pt-2 text-center text-[13px] text-muted">
              {context ? "Pick a quick action below, or ask anything about this message." : "Ask me anything — summaries, replies, rewrites, and more."}
            </div>
          )}

          {turns.map((t, i) => (
            <div key={i} className={t.role === "user" ? "flex justify-end" : "flex justify-start"}>
              <div className={
                t.role === "user"
                  ? "max-w-[85%] rounded-2xl rounded-br-sm bg-accent px-3 py-2 text-[13.5px] text-accent-fg"
                  : `max-w-[90%] rounded-2xl rounded-bl-sm border px-3 py-2 text-[13.5px] ${t.error ? "border-danger/40 bg-danger/10 text-danger" : "border-border bg-panel text-ink/90"}`
              }>
                <div className="whitespace-pre-wrap break-words">{t.text}</div>
                {t.role === "ai" && !t.error && (
                  <button onClick={() => copy(t.text)} className="mt-1.5 flex items-center gap-1 text-[11px] font-semibold text-muted hover:text-ink">
                    <Copy size={11} /> Copy
                  </button>
                )}
              </div>
            </div>
          ))}

          {busy && (
            <div className="flex items-center gap-2 text-[12.5px] text-muted">
              <RefreshCw size={13} className="animate-spin" /> Thinking…
            </div>
          )}
        </div>

        {/* quick actions */}
        <div className="flex flex-wrap gap-1.5 border-t border-border px-3 pt-2.5">
          {QUICK.map((a) => (
            <button
              key={a.label}
              disabled={busy}
              onClick={() => ask(a.prompt, context)}
              className="inline-flex items-center gap-1.5 rounded-pill border border-border bg-panel px-2.5 py-1 text-[12px] font-semibold hover:bg-hover disabled:opacity-40"
            >
              <a.icon size={12} /> {a.label}
            </button>
          ))}
        </div>

        <div className="p-3">
          <div className="flex items-end gap-2 rounded-control border border-border bg-panel p-1.5 focus-within:border-border-strong">
            <textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); ask(input, context); } }}
              rows={1}
              placeholder="Ask the AI…"
              className="max-h-28 min-h-[32px] w-full resize-none bg-transparent px-2 py-1.5 text-[13.5px] outline-none placeholder:text-dim"
            />
            <button
              disabled={busy || !input.trim()}
              onClick={() => ask(input, context)}
              className="grid h-8 w-8 shrink-0 place-items-center rounded-control bg-accent text-accent-fg disabled:opacity-40"
              title="Send"
            >
              <Send size={15} />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
