'use client';

import { useState, useRef, useEffect, FormEvent } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { X, Send, Minus } from 'lucide-react';
import { getAdminToken } from '@/lib/auth';
import { toast } from 'sonner';
import { API_BASE } from '@/lib/config';

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

const AVAILABLE_TOOLS_DESC = `可用工具列表（需要执行操作时，返回 JSON：{"tool":"工具名","params":{...},"description":"简述"}）：

=== 查看 ===
- **get-dashboard**: 仪表盘概览
- **get-analytics-overview**: 数据分析概览
- **list-users**: 用户列表（search?, page?, pageSize?）
- **get-user**: 用户详情（id）
- **list-orders**: 订单列表
- **list-courses**: 课程列表 / **get-course**: 课程详情（id）
- **list-contents**: 内容列表
- **list-prompts**: 提示词列表
- **list-comments**: 评论列表（status?）
- **list-banners**: Banner列表
- **list-notifications**: 通知列表
- **list-config**: 配置列表
- **list-roles**: 角色列表
- **list-admins**: 管理员列表
- **get-enterprise-orgs**: 企业组织列表
- **search**: 全局搜索（q必填, type? 可选 all|users|orders|courses|contents）

=== 创建 ===
- **create-course**: 创建课程（title必填, description?, price?, isFree?, status?）
- **create-content**: 创建内容（title必填, summary?, content?, tags?, status?）
- **create-prompt**: 创建提示词（title必填, content必填, description?, tags?, status?）
- **create-banner**: 创建Banner（title必填, image必填, link?, position?, sortOrder?）
- **create-notification**: 创建通知（title必填, content?, link?, userId?）
- **create-role**: 创建角色（name必填, description?, permissions?）
- **create-admin**: 创建管理员（username必填, password必填, nickname?, roleId?）
- **create-organization**: 创建企业组织（name必填, description?, contactName?, contactPhone?）

=== 修改 ===
- **update-user**: 修改用户（id, nickname?, phone?, email?, status?, memberPlan?, sandboxDaily?）
- **update-user-status**: 修改用户状态（id, status: ACTIVE|INACTIVE|BANNED）
- **update-course**: 修改课程（id, title?, description?, price?, isFree?, status?）
- **update-content**: 修改内容（id, title?, summary?, content?, tags?, status?）
- **update-prompt**: 修改提示词（id, title?, content?, description?, tags?, status?）
- **update-banner**: 修改Banner（id, title?, image?, link?, sortOrder?）
- **update-config**: 修改配置（key必填, value必填, category?, description?）
- **update-role**: 修改角色（id, name?, description?, permissions?）
- **update-admin**: 修改管理员（id, nickname?, roleId?, password?）
- **update-organization**: 修改企业组织（id, name?, description?, contactName?, contactPhone?）
- **toggle-course-status**: 切换课程上下架（id）
- **toggle-content-status**: 切换内容上下架（id）
- **toggle-prompt-status**: 切换提示词上下架（id）

=== 删除 ===
- **delete-user**: 删除用户（id）
- **delete-course**: 删除课程（id）
- **delete-content**: 删除内容（id）
- **delete-prompt**: 删除提示词（id）
- **delete-banner**: 删除Banner（id）
- **delete-notification**: 删除通知（id）
- **delete-role**: 禁用角色（id）
- **delete-admin**: 禁用管理员（id）
- **delete-organization**: 删除组织（id）
- **add-org-member**: 添加组织成员（organizationId, userId, role?）
- **remove-org-member**: 移除组织成员（organizationId, userId）

=== 导航 ===
- **navigate**: 跳转到页面（path: /admin/users等）

=== 通知管理 ===
- **mark-all-notifications-read**: 将所有通知标记为已读

当用户请求执行操作时，先调用对应工具。工具执行完毕后会用自然语言总结结果。`;

const SYSTEM_PROMPT = `你是宇之然AI管理后台的智能助手，帮助管理员完成日常运营工作。
你可以：
1. 回答管理员的问题
2. 调用工具执行操作（如查看数据、管理用户、审核评论等）
3. 跳转到各个管理页面

${AVAILABLE_TOOLS_DESC}

注意：每次只需要返回一个 JSON 工具调用，不要包含多余文字。执行结果会自动呈现给用户。`;

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;
}

async function postChat(messages: { role: string; content: string }[]): Promise<string> {
  const tk = getAdminToken();
  if (!tk) return '请先登录管理账号';
  const res = await fetch(`${API_BASE}/admin/ai-assistant/chat`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tk}` },
    body: JSON.stringify({ messages }),
  });
  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 = getAdminToken();
  const res = await fetch(`${API_BASE}/admin/ai-assistant/action`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tk}` },
    body: JSON.stringify({ tool, params, messages }),
  });
  const data = await res.json();
  if (!res.ok) throw new Error(data.message || '工具执行失败');
  return data;
}

export function AdminAIAssistant() {
  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 messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

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

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

  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 apiMessages = [
        { role: 'system', content: SYSTEM_PROMPT },
        ...messages.map(m => ({ role: m.role, content: m.content })),
        { role: 'user', content: text },
      ];

      let reply = await postChat(apiMessages);
      const toolCall = parseToolCall(reply);

      if (toolCall) {
        if (toolCall.tool === 'navigate') {
          const path = toolCall.params.path;
          setMessages(prev => [...prev, { role: 'assistant', content: `正在跳转到 ${path}...` }]);
          toast.success(toolCall.description || `跳转到 ${path}`);
          router.push(path);
        } else {
          const result = await executeTool(toolCall.tool, toolCall.params, apiMessages);
          reply = result.reply;
          setMessages(prev => [...prev, { role: 'assistant', content: 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 (
      <button
        onClick={() => setOpen(true)}
        className="fixed bottom-6 right-6 z-50 flex items-center gap-2 px-4 py-2.5 bg-purple-600 text-white rounded-full shadow-lg hover:bg-purple-700 hover:shadow-xl hover:scale-105 transition-all"
      >
        <span className="relative flex h-2 w-2">
          <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 w-2 bg-white"></span>
        </span>
        <span className="text-sm font-medium">运营助手</span>
      </button>
    );
  }

  const starters = ['查看仪表盘数据', '列出最近用户', '搜索订单', '查看待审核评论', '查看企业版组织', '列出所有角色', '帮我查一下最近的课程'];

  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(500px, 80vh)' }}
      >
        <div className="flex items-center justify-between px-4 py-3 border-b border-border bg-purple-500/10">
          <div className="flex items-center gap-2">
            <div className="w-7 h-7 bg-purple-600 rounded-lg flex items-center justify-center text-white text-xs font-bold">AI</div>
            <span className="text-sm font-semibold text-foreground">运营助手</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">
              <Minus className="w-4 h-4" />
            </button>
            <button onClick={() => { setOpen(false); setMinimized(false); setMessages([]); }} className="p-1.5 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg">
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>

        {!minimized && (
          <>
            <div className="overflow-y-auto p-3 space-y-3" style={{ maxHeight: '320px' }}>
              {messages.length === 0 && (
                <div className="mb-2">
                  <p className="text-xs text-muted-foreground mb-3">
                    你好！我是运营助手，可以帮你查询数据、管理用户、审核内容等。试试这些：
                  </p>
                  <div className="flex flex-wrap gap-1.5">
                    {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">
                        {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-purple-600 rounded-lg flex items-center justify-center text-white text-[10px] font-bold shrink-0 mt-0.5">AI</div>
                  )}
                  <div className={`max-w-[85%] rounded-2xl px-3 py-2 text-sm ${
                    msg.role === 'user' ? 'bg-purple-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-purple-600 rounded-lg flex items-center justify-center text-white text-[10px] font-bold shrink-0">AI</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="输入问题或指令..."
                  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-purple-500 disabled:opacity-50"
                />
                <button type="submit" disabled={sending || !input.trim()}
                  className="p-2 bg-purple-600 text-white rounded-xl hover:bg-purple-700 disabled:opacity-50">
                  <Send className="w-4 h-4" />
                </button>
              </form>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
