'use client';

import { useState, useRef, useEffect, FormEvent } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { X, Send, Minus, Sparkles } from 'lucide-react';
import { executeClientAction } from '@/lib/assistant-actions';
import { useT } from '@/i18n';
import { getToken, apiFetch } from '@/lib/auth';
import { toast } from 'sonner';

interface Message {
  role: 'user' | 'assistant';
  content: string;
}

const PAGE_CONTEXTS: Record<string, { greeting: string; starters: string[] }> = {
  '/': {
    greeting: '你好！我是宇之然 AI 助手，可以帮你了解平台功能、搜索内容、查看学习进度等。试试下面的问题：',
    starters: ['宇之然 AI 能做什么？', '如何开始学习 AI？', '搜索一些课程', '推荐一个学习路线', '查看有哪些技能'],
  },
  '/sandbox': {
    greeting: '我在 AI 沙盒页面，可以帮你了解沙盒功能、切换模型、开始对话等。',
    starters: ['如何切换模型？', '高级参数怎么调？', '如何查看历史记录？', '对话次数限制是多少'],
  },
  '/skills': {
    greeting: '我在技能库页面，可以帮你了解各种技能、推荐适合你的技能。',
    starters: ['有哪些技能可以学习？', '如何选择适合我的技能？', '有哪些入门技能？', '如何开始练习一个技能？'],
  },
  '/learning': {
    greeting: '我在学习路径页面，可以帮你分析学习情况、推荐学习内容。',
    starters: ['查看我的学情分析', '学习路径有哪些阶段？', '我有哪些薄弱环节', '推荐学习内容'],
  },
  '/my': {
    greeting: '我在个人中心页面，可以帮你管理账户、查看会员信息等。',
    starters: ['查看个人信息', '我的会员状态', '查看订单记录', '查看通知'],
  },
  '/models': {
    greeting: '我在模型百科页面，可以帮你了解各种 AI 模型的特点和用途。',
    starters: ['有哪些模型可以参考？', '如何选择合适的模型？', '模型能力怎么对比？', '查看所有模型'],
  },
  '/prompts': {
    greeting: '我在提示词工坊页面，可以帮你了解提示词编写技巧。',
    starters: ['如何编写一个好的提示词？', '查看有哪些提示词', '如何测试提示词效果？'],
  },
  '/courses': {
    greeting: '我在课程专题页面，可以帮你选择课程、规划学习。',
    starters: ['有哪些课程可以学习？', '如何选择适合我的课程？', '有免费的课程吗？', '搜索课程'],
  },
  '/compare': {
    greeting: '我在对比实验室页面，可以帮你了解如何使用对比功能。',
    starters: ['对比实验室怎么用？', '如何添加对比模型？', '对比结果怎么看？'],
  },
};

function getPageContext(pathname: string) {
  const sorted = Object.keys(PAGE_CONTEXTS).sort((a, b) => b.length - a.length);
  for (const key of sorted) {
    if (pathname.startsWith(key)) return PAGE_CONTEXTS[key];
  }
  return PAGE_CONTEXTS['/'];
}

function parseToolCall(text: string): { tool: string; params: Record<string, any>; description?: string } | null {
  let braceDepth = 0;
  let start = -1;
  for (let i = 0; i < text.length; i++) {
    if (text[i] === '{') {
      if (start === -1) start = i;
      braceDepth++;
    } else if (text[i] === '}') {
      braceDepth--;
      if (braceDepth === 0 && start !== -1) {
        try {
          const parsed = JSON.parse(text.slice(start, i + 1));
          if (parsed.tool) return parsed;
        } catch {}
        start = -1;
      }
    }
  }
  return null;
}

export function AIAssistant() {
  const t = useT();
  const pathname = usePathname();
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [minimized, setMinimized] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const [pageCtx, setPageCtx] = useState(getPageContext(pathname));
  const [started, setStarted] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setPageCtx(getPageContext(pathname));
  }, [pathname]);

  useEffect(() => {
    if (open && !started) {
      setPageCtx(getPageContext(pathname));
      setStarted(true);
    }
  }, [open, pathname, started]);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  useEffect(() => {
    if (open) inputRef.current?.focus();
  }, [open]);

  async function postChat(messages: { role: string; content: string }[], pageContext?: string): Promise<string> {
    const tk = getToken();
    if (!tk) throw new Error('请先登录');
    const res = await apiFetch('/ai-assistant/chat', {
      method: 'POST',
      body: JSON.stringify({ messages, pageContext }),
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.message || '请求失败');
    return data.reply;
  }

  async function executeTool(tool: string, params: Record<string, any>, messages: { role: string; content: string }[]): Promise<{ reply: string }> {
    const tk = getToken();
    const res = await apiFetch('/ai-assistant/action', {
      method: 'POST',
      body: JSON.stringify({ tool, params, messages }),
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.message || '工具执行失败');
    return data;
  }

  async function handleSend(e: FormEvent) {
    e.preventDefault();
    const text = input.trim();
    if (!text || sending) return;

    const userMsg: Message = { role: 'user', content: text };
    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setSending(true);

    try {
      const tk = getToken();
      if (!tk) {
        const reply = '📝 登录后可体验完整 AI 对话功能。\n\n点击右上角「登录」或「注册」即可开始使用，解锁 AI 助手的全部能力。';
        setMessages(prev => [...prev, { role: 'assistant', content: reply }]);
        return;
      }

      const apiMessages = [
        ...messages.filter(m => m.role === 'user' || m.role === 'assistant').map(m => ({ role: m.role, content: m.content })),
        { role: 'user', content: text },
      ];

      const currentPage = pathname.split('/').filter(Boolean)[0] || '首页';
      let reply = await postChat(apiMessages, currentPage);
      const toolCall = parseToolCall(reply);

      if (toolCall) {
        const clientActions = ['navigate', 'setModel', 'startChat', 'openSkill', 'setParameter'];
        if (clientActions.includes(toolCall.tool)) {
          setMessages(prev => [...prev, { role: 'assistant', content: `正在${toolCall.description || '执行操作'}...` }]);
          const result = await executeClientAction(toolCall.tool, toolCall.params, router);
          if (result.success) {
            toast.success(result.message, { icon: <Sparkles className="w-4 h-4" /> });
          } else {
            toast.error(result.message);
          }
        } else {
          const result = await executeTool(toolCall.tool, toolCall.params, apiMessages);
          setMessages(prev => [...prev, { role: 'assistant', content: result.reply }]);
        }
      } else {
        setMessages(prev => [...prev, { role: 'assistant', content: reply }]);
      }
    } catch (e: any) {
      setMessages(prev => [...prev, { role: 'assistant', content: `出错啦：${e.message}` }]);
    } finally {
      setSending(false);
    }
  }

  function handleStarter(starter: string) {
    setInput(starter);
    setTimeout(() => inputRef.current?.focus(), 0);
  }

  if (!open) {
    return (
      <div className="fixed bottom-6 right-6 z-50 flex items-center gap-3">
        <div className="relative group">
          <div className="absolute -top-10 left-1/2 -translate-x-1/2 px-3 py-1.5 bg-muted text-muted-foreground text-xs rounded-lg opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none">
            {t.assistant?.title || 'AI 助手'}
            <div className="absolute -bottom-1 left-1/2 -translate-x-1/2 w-2 h-2 bg-muted rotate-45" />
          </div>
          <button
            onClick={() => setOpen(true)}
            className="flex items-center gap-2 px-4 py-2.5 bg-brand-600 text-white rounded-full shadow-lg hover:bg-brand-700 hover:shadow-xl hover:scale-105 transition-all"
          >
            <span className="relative flex h-2.5 w-2.5">
              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-white opacity-75"></span>
              <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-white"></span>
            </span>
            <span className="text-sm font-medium">{t.assistant?.title || 'AI 助手'}</span>
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed bottom-6 right-6 z-50 flex flex-col items-end gap-2">
      <div
        className={`bg-card border border-border rounded-2xl shadow-2xl overflow-hidden transition-all duration-300 ${
          minimized ? 'h-14 w-72' : 'w-80 sm:w-96'
        }`}
        style={{ maxHeight: 'min(600px, 80vh)' }}
      >
        <div className="flex items-center justify-between px-4 py-3 border-b border-border bg-muted/30">
          <div className="flex items-center gap-2">
            <div className="w-7 h-7 bg-brand-600 rounded-lg flex items-center justify-center text-white text-xs font-bold">Y</div>
            <span className="text-sm font-semibold text-foreground">{t.assistant?.title || 'AI 助手'}</span>
          </div>
          <div className="flex items-center gap-1">
            <button onClick={() => setMinimized(!minimized)} className="p-1.5 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors">
              <Minus className="w-4 h-4" />
            </button>
            <button onClick={() => { setOpen(false); setMinimized(false); setStarted(false); setMessages([]); }} className="p-1.5 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors">
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>

        {!minimized && (
          <>
            <div className="overflow-y-auto p-3 space-y-3" style={{ maxHeight: '360px' }}>
              {messages.length === 0 && (
                <div className="mb-2">
                  <p className="text-xs text-muted-foreground mb-3 leading-relaxed">
                    {pageCtx.greeting}
                  </p>
                  <div className="flex flex-wrap gap-1.5">
                    {pageCtx.starters.map((q, i) => (
                      <button
                        key={i}
                        onClick={() => handleStarter(q)}
                        className="text-xs px-2.5 py-1.5 bg-muted text-muted-foreground rounded-full border border-border hover:bg-accent hover:text-foreground transition-colors"
                      >
                        {q}
                      </button>
                    ))}
                  </div>
                </div>
              )}
              {messages.map((msg, i) => (
                <div key={i} className={`flex items-start gap-2 ${msg.role === 'user' ? 'justify-end' : ''}`}>
                  {msg.role === 'assistant' && (
                    <div className="w-6 h-6 bg-brand-600 rounded-lg flex items-center justify-center text-white text-[10px] font-bold shrink-0 mt-0.5">Y</div>
                  )}
                  <div
                    className={`max-w-[85%] rounded-2xl px-3 py-2 text-sm leading-relaxed whitespace-pre-wrap ${
                      msg.role === 'user'
                        ? 'bg-brand-600 text-white rounded-tr-none'
                        : 'bg-muted text-foreground rounded-tl-none'
                    }`}
                  >
                    {msg.content}
                  </div>
                  {msg.role === 'user' && (
                    <div className="w-6 h-6 bg-muted-foreground/20 rounded-lg flex items-center justify-center text-[10px] font-bold shrink-0 mt-0.5">我</div>
                  )}
                </div>
              ))}
              {sending && (
                <div className="flex items-start gap-2">
                  <div className="w-6 h-6 bg-brand-600 rounded-lg flex items-center justify-center text-white text-[10px] font-bold shrink-0 mt-0.5">Y</div>
                  <div className="bg-muted rounded-2xl rounded-tl-none px-3 py-2">
                    <span className="inline-flex gap-1">
                      <span className="w-1.5 h-1.5 bg-muted-foreground/40 rounded-full animate-bounce" />
                      <span className="w-1.5 h-1.5 bg-muted-foreground/40 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
                      <span className="w-1.5 h-1.5 bg-muted-foreground/40 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
                    </span>
                  </div>
                </div>
              )}
              <div ref={messagesEndRef} />
            </div>

            <div className="border-t border-border p-3">
              <form onSubmit={handleSend} className="flex gap-2">
                <input
                  ref={inputRef}
                  type="text"
                  value={input}
                  onChange={e => setInput(e.target.value)}
                  placeholder={t.assistant?.placeholder || '输入你的问题...'}
                  disabled={sending}
                  className="flex-1 px-3 py-2 bg-background border border-input rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"
                />
                <button
                  type="submit"
                  disabled={sending || !input.trim()}
                  className="p-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 disabled:opacity-50"
                >
                  <Send className="w-4 h-4" />
                </button>
              </form>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
