"use client";

/**
 * AI Avatar Panel
 * ----------------
 * A right-side slide-out panel that contains:
 *   - Conversation messages
 *   - Suggested prompts
 *   - Chat input
 *
 * It sends messages to POST /api/ai-avatar and displays responses.
 */

import { useState, useRef, useEffect } from "react";
import { usePathname } from "next/navigation";
import { useBrand } from "@/context/brand-context";
import { useRouter } from "next/navigation";
import {
  X, Send, Sparkles, MessageSquare, Lightbulb, Loader2,
  ArrowRight, ClipboardPlus, FileBarChart, Search, Wrench, FilePlus, Download,
  CheckCircle2, Copy,
} from "lucide-react";

// ─── Types ───────────────────────────────────────────────────────────────────

interface SuggestedAction {
  type: "navigate" | "create_task" | "generate_report" | "run_audit" | "create_brief" | "export";
  label: string;
  href?: string;
  payload?: Record<string, string>;
}

interface SuggestedFollowUp {
  prompt: string;
}

interface Message {
  id: string;
  role: "user" | "assistant";
  content: string;
  context?: { module: string; brand: string; page: string; metrics: Record<string, string | number> };
  actions?: SuggestedAction[];
  followUps?: SuggestedFollowUp[];
}

// ─── Suggested prompts (context-aware) ───────────────────────────────────────

function getSuggestedPrompts(page: string): string[] {
  const base = [
    "What should I focus on this week?",
    "Where am I losing the most traffic?",
  ];

  if (page.startsWith("/dashboard")) {
    return [
      "How is my traffic trending?",
      "What are my top priorities right now?",
      "Which channel is growing fastest?",
      ...base,
    ];
  }
  if (page.startsWith("/technical-audit")) {
    return [
      "What are my most critical technical issues?",
      "Which fixes will have the biggest impact?",
      "How does my site health compare to competitors?",
      ...base,
    ];
  }
  if (page.startsWith("/competitors")) {
    return [
      "Who is my biggest threat and why?",
      "Where can I beat my competitors?",
      "Which competitor is growing fastest?",
      ...base,
    ];
  }
  if (page.startsWith("/conversion-intelligence") || page.startsWith("/site-tag-analytics")) {
    return [
      "How are my conversions performing?",
      "Which channel has the best ROI?",
      "Where am I losing conversions?",
      ...base,
    ];
  }
  if (page.startsWith("/content-brief") || page.startsWith("/llmo-content-brief")) {
    return [
      "What content should I publish next?",
      "How can I improve my content scores?",
      "Which keywords should I target?",
      ...base,
    ];
  }

  return [
    "Give me a summary of my performance",
    "What are my top 3 priorities?",
    "How can I improve my rankings?",
    ...base,
  ];
}

// ─── Component ───────────────────────────────────────────────────────────────

export function AiAvatarPanel({
  open,
  onClose,
}: {
  open: boolean;
  onClose: () => void;
}) {
  const pathname = usePathname();
  const router = useRouter();
  const { brand } = useBrand();

  const [messages, setMessages] = useState<Message[]>([]);
  const [actionFeedback, setActionFeedback] = useState<Record<string, string>>({});
  const [summaryText, setSummaryText] = useState<string | null>(null);
  const [summaryCopied, setSummaryCopied] = useState(false);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [conversationId, setConversationId] = useState<string | null>(null);
  const [showHistory, setShowHistory] = useState(false);
  const [recentConvos, setRecentConvos] = useState<Array<{ id: string; title: string; updatedAt: string; messageCount: number; lastMessage: string }>>([]);
  const scrollRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // Auto-scroll to bottom when new messages arrive
  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages]);

  // Focus input when panel opens + load recent conversations
  useEffect(() => {
    if (open) {
      setTimeout(() => inputRef.current?.focus(), 200);
      // Load recent conversations for the history sidebar
      fetch(`/api/ai-avatar/conversations?brandId=${brand.id}`)
        .then(r => r.ok ? r.json() : [])
        .then(data => { if (Array.isArray(data)) setRecentConvos(data); })
        .catch(() => {});
    }
  }, [open, brand.id]);

  // ── Send a message ──
  async function sendMessage(text: string) {
    if (!text.trim() || loading) return;

    const userMsg: Message = {
      id: `user-${Date.now()}`,
      role: "user",
      content: text.trim(),
    };
    setMessages((prev) => [...prev, userMsg]);
    setInput("");
    setLoading(true);

    try {
      const res = await fetch("/api/ai-avatar", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          brandId: brand.id,
          currentPage: pathname,
          message: text.trim(),
          conversationId,
          history: messages.map((m) => ({
            role: m.role,
            content: m.content,
          })),
        }),
      });

      const data = await res.json();

      // Track the conversation ID returned by the backend
      if (data.conversationId) setConversationId(data.conversationId);

      const assistantMsg: Message = {
        id: `asst-${Date.now()}`,
        role: "assistant",
        content: data.reply ?? "Sorry, I couldn't generate a response. Please try again.",
        context: data.context ?? undefined,
        actions: data.actions ?? [],
        followUps: data.followUps ?? [],
      };
      setMessages((prev) => [...prev, assistantMsg]);
    } catch {
      setMessages((prev) => [
        ...prev,
        {
          id: `err-${Date.now()}`,
          role: "assistant",
          content: "Something went wrong. Please try again.",
        },
      ]);
    } finally {
      setLoading(false);
    }
  }

  // ── Load a saved conversation ──
  async function loadConversation(id: string) {
    try {
      const res = await fetch(`/api/ai-avatar/conversations?id=${id}`);
      if (!res.ok) return;
      const data = await res.json();
      setConversationId(data.id);
      setMessages(
        data.messages.map((m: { id: string; role: string; content: string; metadata: Record<string, unknown> }) => ({
          id: m.id,
          role: m.role as "user" | "assistant",
          content: m.content,
          context: (m.metadata as Record<string, unknown>)?.context as Message["context"] | undefined,
          actions: (m.metadata as Record<string, unknown>)?.actions as Message["actions"] | undefined,
          followUps: (m.metadata as Record<string, unknown>)?.followUps as Message["followUps"] | undefined,
        }))
      );
      setShowHistory(false);
    } catch { /* ignore */ }
  }

  // ── Start a new conversation ──
  function startNewConversation() {
    setMessages([]);
    setConversationId(null);
    setShowHistory(false);
    setActionFeedback({});
  }

  // ── Execute an action via the backend ──
  async function executeAction(
    action: SuggestedAction,
    feedbackKey: string
  ) {
    // Navigate actions are handled client-side only
    if (action.type === "navigate" && action.href) {
      router.push(action.href);
      onClose();
      return;
    }

    setActionFeedback(prev => ({ ...prev, [feedbackKey]: "Working..." }));

    try {
      const res = await fetch("/api/ai-avatar/execute", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          actionType: action.type,
          brandId: brand.id,
          currentPage: pathname,
          payload: action.payload ?? {},
        }),
      });

      const result = await res.json();

      if (result.ok) {
        setActionFeedback(prev => ({ ...prev, [feedbackKey]: result.message }));

        // If this was a report generation, show the summary
        if (action.type === "generate_report" && result.data?.summary) {
          setSummaryText(result.data.summary as string);
        }
      } else {
        setActionFeedback(prev => ({ ...prev, [feedbackKey]: result.message || "Failed" }));
        setTimeout(() => setActionFeedback(prev => { const n = { ...prev }; delete n[feedbackKey]; return n; }), 3000);
      }
    } catch {
      setActionFeedback(prev => ({ ...prev, [feedbackKey]: "Error — try again" }));
      setTimeout(() => setActionFeedback(prev => { const n = { ...prev }; delete n[feedbackKey]; return n; }), 3000);
    }
  }

  const prompts = getSuggestedPrompts(pathname);

  if (!open) return null;

  return (
    <>
      {/* Backdrop */}
      <div
        className="fixed inset-0 bg-black/20 z-40 lg:hidden"
        onClick={onClose}
      />

      {/* Panel */}
      <div className="fixed right-0 top-0 bottom-0 w-full max-w-md bg-white border-l border-slate-200 shadow-2xl z-50 flex flex-col">

        {/* ── Header ── */}
        <div className="px-5 py-4 border-b border-slate-100 flex items-center gap-3 shrink-0">
          <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-brand-500 to-violet-600 flex items-center justify-center shrink-0 shadow-sm">
            <Sparkles className="w-4.5 h-4.5 text-white" />
          </div>
          <div className="flex-1 min-w-0">
            <h2 className="text-sm font-bold text-slate-900">meSEO AI Strategist</h2>
            <p className="text-[11px] text-slate-400 truncate">
              {brand.name} · {pathname.split("/").pop() || "Dashboard"}
            </p>
          </div>
          <button
            onClick={startNewConversation}
            title="New conversation"
            className="w-8 h-8 rounded-lg hover:bg-slate-100 flex items-center justify-center transition-colors"
          >
            <FilePlus className="w-4 h-4 text-slate-400" />
          </button>
          <button
            onClick={() => setShowHistory(!showHistory)}
            title="Conversation history"
            className={`w-8 h-8 rounded-lg flex items-center justify-center transition-colors ${showHistory ? "bg-brand-50 text-brand-600" : "hover:bg-slate-100 text-slate-400"}`}
          >
            <MessageSquare className="w-4 h-4" />
          </button>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-lg hover:bg-slate-100 flex items-center justify-center transition-colors"
          >
            <X className="w-4 h-4 text-slate-400" />
          </button>
        </div>

        {/* ── Messages ── */}
        {/* ── History sidebar ── */}
        {showHistory && (
          <div className="flex-1 overflow-y-auto border-b border-slate-100">
            <div className="px-5 py-3 border-b border-slate-50 flex items-center justify-between">
              <p className="text-xs font-bold text-slate-400 uppercase tracking-widest">Recent Conversations</p>
              <span className="text-[10px] text-slate-300">{recentConvos.length}</span>
            </div>
            {recentConvos.length === 0 ? (
              <div className="px-5 py-10 text-center">
                <p className="text-sm text-slate-400">No conversations yet.</p>
                <p className="text-xs text-slate-300 mt-1">Start chatting to create your first one.</p>
              </div>
            ) : (
              <ul className="divide-y divide-slate-50">
                {recentConvos.map((c) => (
                  <li key={c.id}>
                    <button
                      onClick={() => loadConversation(c.id)}
                      className={`w-full text-left px-5 py-3.5 hover:bg-slate-50 transition-colors ${conversationId === c.id ? "bg-brand-50 border-l-2 border-brand-500" : ""}`}
                    >
                      <p className="text-sm font-semibold text-slate-800 truncate">{c.title}</p>
                      <p className="text-[11px] text-slate-400 mt-0.5 truncate">{c.lastMessage}</p>
                      <p className="text-[10px] text-slate-300 mt-1">
                        {c.messageCount} message{c.messageCount !== 1 ? "s" : ""} · {new Date(c.updatedAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                      </p>
                    </button>
                  </li>
                ))}
              </ul>
            )}
          </div>
        )}

        {/* ── Messages ── */}
        {!showHistory && <div ref={scrollRef} className="flex-1 overflow-y-auto px-5 py-4 space-y-4">

          {/* Empty state with suggested prompts */}
          {messages.length === 0 && (
            <div className="space-y-4">
              {/* Welcome */}
              <div className="bg-gradient-to-br from-brand-50 to-violet-50 rounded-xl border border-brand-100 p-4">
                <div className="flex items-center gap-2 mb-2">
                  <Sparkles className="w-4 h-4 text-brand-600" />
                  <p className="text-xs font-bold text-brand-700 uppercase tracking-wide">AI Strategist</p>
                </div>
                <p className="text-sm text-slate-700 leading-relaxed">
                  Hi! I&apos;m your meSEO AI Strategist. I can analyze your data, explain what&apos;s happening, and tell you exactly what to do next. Ask me anything about your SEO, traffic, competitors, or content.
                </p>
              </div>

              {/* Suggested prompts */}
              <div>
                <div className="flex items-center gap-1.5 mb-2">
                  <Lightbulb className="w-3.5 h-3.5 text-amber-500" />
                  <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Suggested Questions</p>
                </div>
                <div className="space-y-1.5">
                  {prompts.map((prompt, i) => (
                    <button
                      key={i}
                      onClick={() => sendMessage(prompt)}
                      className="w-full text-left px-3.5 py-2.5 rounded-lg border border-slate-200 text-sm text-slate-700 hover:bg-brand-50 hover:border-brand-200 hover:text-brand-700 transition-colors"
                    >
                      {prompt}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* Conversation */}
          {messages.map((msg) => (
            <div key={msg.id}>
              {/* Context chip for assistant messages */}
              {msg.role === "assistant" && msg.context && (
                <div className="flex justify-start mb-1.5">
                  <div className="flex items-center gap-1.5 text-[10px] font-semibold text-slate-400 bg-white border border-slate-200 rounded-full px-2.5 py-1">
                    <Sparkles className="w-3 h-3 text-brand-500" />
                    <span>Analyzed: <span className="text-slate-600">{msg.context.module}</span></span>
                    <span className="text-slate-300">·</span>
                    <span className="text-slate-600">{msg.context.brand}</span>
                  </div>
                </div>
              )}
              <div className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}>
                <div
                  className={`max-w-[85%] rounded-xl px-4 py-3 ${
                    msg.role === "user"
                      ? "bg-brand-600 text-white"
                      : "bg-slate-100 text-slate-800"
                  }`}
                >
                {msg.role === "assistant" ? (
                  <div className="text-sm leading-relaxed space-y-2">
                    {msg.content.split("\n").map((line, i) => {
                      if (line.startsWith("**") && line.endsWith("**")) {
                        return (
                          <p key={i} className="font-bold text-slate-900 text-xs uppercase tracking-wide mt-3 first:mt-0">
                            {line.replace(/\*\*/g, "")}
                          </p>
                        );
                      }
                      if (line.match(/^\d+\./)) {
                        return (
                          <p key={i} className="text-sm pl-1">
                            {line}
                          </p>
                        );
                      }
                      if (line.trim() === "") return null;
                      return <p key={i}>{line}</p>;
                    })}
                  </div>
                ) : (
                  <p className="text-sm">{msg.content}</p>
                )}
              </div>
            </div>

              {/* Suggested actions */}
              {msg.role === "assistant" && msg.actions && msg.actions.length > 0 && (
                <div className="flex justify-start mt-2">
                  <div className="flex flex-wrap gap-1.5 max-w-[85%]">
                    {msg.actions.map((action, ai) => {
                      const key = `${msg.id}-action-${ai}`;
                      const fb = actionFeedback[key];
                      const iconMap: Record<string, React.ReactNode> = {
                        navigate: <ArrowRight className="w-3 h-3" />,
                        create_task: <ClipboardPlus className="w-3 h-3" />,
                        generate_report: <FileBarChart className="w-3 h-3" />,
                        run_audit: <Wrench className="w-3 h-3" />,
                        create_brief: <FilePlus className="w-3 h-3" />,
                        export: <Download className="w-3 h-3" />,
                      };
                      return (
                        <button
                          key={ai}
                          disabled={!!fb}
                          onClick={() => executeAction(action, key)}
                          className={`inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-semibold border transition-colors ${
                            fb
                              ? "border-green-200 bg-green-50 text-green-700"
                              : action.type === "navigate"
                                ? "border-brand-200 bg-brand-50 text-brand-700 hover:bg-brand-100"
                                : action.type === "create_task"
                                  ? "border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"
                                  : action.type === "generate_report"
                                    ? "border-violet-200 bg-violet-50 text-violet-700 hover:bg-violet-100"
                                    : "border-slate-200 bg-white text-slate-600 hover:bg-slate-50"
                          }`}
                        >
                          {fb ? (fb === "Working..." ? <Loader2 className="w-3 h-3 animate-spin" /> : <CheckCircle2 className="w-3 h-3" />) : iconMap[action.type]}
                          {fb || action.label}
                        </button>
                      );
                    })}
                  </div>
                </div>
              )}

              {/* Follow-up prompts */}
              {msg.role === "assistant" && msg.followUps && msg.followUps.length > 0 && (
                <div className="flex justify-start mt-2">
                  <div className="flex flex-wrap gap-1.5 max-w-[85%]">
                    {msg.followUps.map((fu, fi) => (
                      <button
                        key={fi}
                        onClick={() => sendMessage(fu.prompt)}
                        disabled={loading}
                        className="text-[11px] font-semibold text-slate-500 bg-white border border-slate-200 hover:bg-brand-50 hover:text-brand-600 hover:border-brand-200 px-2.5 py-1.5 rounded-lg transition-colors"
                      >
                        {fu.prompt}
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </div>
          ))}

          {/* Loading indicator */}
          {loading && (
            <div className="flex justify-start">
              <div className="bg-slate-100 rounded-xl px-4 py-3 flex items-center gap-2">
                <Loader2 className="w-4 h-4 text-brand-500 animate-spin" />
                <span className="text-sm text-slate-500">Thinking...</span>
              </div>
            </div>
          )}
        </div>}

        {/* ── Input bar ── */}
        <div className="px-4 py-3 border-t border-slate-100 shrink-0 bg-white">
          <div className="flex items-center gap-2">
            <div className="relative flex-1">
              <MessageSquare className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" />
              <input
                ref={inputRef}
                type="text"
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendMessage(input); } }}
                placeholder="Ask your AI strategist..."
                disabled={loading}
                className="w-full pl-10 pr-4 py-2.5 rounded-xl border border-slate-200 text-sm text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-brand-500/30 focus:border-brand-300 disabled:opacity-50 transition"
              />
            </div>
            <button
              onClick={() => sendMessage(input)}
              disabled={!input.trim() || loading}
              className="w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center hover:bg-brand-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors shrink-0"
            >
              <Send className="w-4 h-4" />
            </button>
          </div>
        </div>

        {/* ── Summary overlay ── */}
        {summaryText && (
          <div className="absolute inset-0 bg-white z-10 flex flex-col">
            <div className="px-5 py-4 border-b border-slate-100 flex items-center gap-3 shrink-0">
              <FileBarChart className="w-5 h-5 text-violet-600" />
              <div className="flex-1">
                <h3 className="text-sm font-bold text-slate-900">Generated Summary</h3>
                <p className="text-[11px] text-slate-400">Copy and share with clients or stakeholders</p>
              </div>
              <button
                onClick={() => { setSummaryText(null); setSummaryCopied(false); }}
                className="w-8 h-8 rounded-lg hover:bg-slate-100 flex items-center justify-center transition-colors"
              >
                <X className="w-4 h-4 text-slate-400" />
              </button>
            </div>
            <div className="flex-1 overflow-y-auto px-5 py-4">
              <pre className="text-sm text-slate-700 leading-relaxed whitespace-pre-wrap font-sans bg-slate-50 rounded-xl border border-slate-200 p-4">
                {summaryText}
              </pre>
            </div>
            <div className="px-5 py-3 border-t border-slate-100 flex items-center gap-2 shrink-0">
              <button
                onClick={() => {
                  navigator.clipboard.writeText(summaryText);
                  setSummaryCopied(true);
                  setTimeout(() => setSummaryCopied(false), 2000);
                }}
                className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-xl text-sm font-semibold transition-colors ${
                  summaryCopied
                    ? "bg-green-600 text-white"
                    : "bg-brand-600 text-white hover:bg-brand-700"
                }`}
              >
                {summaryCopied ? <CheckCircle2 className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
                {summaryCopied ? "Copied!" : "Copy to Clipboard"}
              </button>
              <button
                onClick={() => { setSummaryText(null); setSummaryCopied(false); }}
                className="px-4 py-2.5 rounded-xl text-sm font-semibold text-slate-600 bg-slate-100 hover:bg-slate-200 transition-colors"
              >
                Back to Chat
              </button>
            </div>
          </div>
        )}
      </div>
    </>
  );
}
