﻿﻿﻿import React, { useEffect, useState } from 'react';
import { message, Switch, Tag, Modal, Form, Input, Button } from 'antd';
import { useNavigate } from 'react-router-dom';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import useAuthStore from '../store/authStore';
import api from '../services/api';
import './AdminDashboard.css';

const AdminDashboard = () => {
  const navigate = useNavigate();
  const { user, logout, token } = useAuthStore();
  const [activeNav, setActiveNav] = useState('users');
  const [stats, setStats] = useState({});
  const [users, setUsers] = useState([]);
  const [chatLogs, setChatLogs] = useState([]);
  const [searchKeyword, setSearchKeyword] = useState('');

  useEffect(() => {
    if (!token) { navigate('/login'); return; }
    fetchStats();
    fetchUsers();
  }, [token, navigate]);

  const fetchStats = async () => {
    try {
      const res = await api.get('/admin/dashboard-stats');
      setStats(res.data);
    } catch (e) { message.error('获取统计数据失败'); }
  };

  const fetchUsers = async (search = '') => {
    try {
      const params = search ? { search } : {};
      const res = await api.get('/admin/users', { params });
      setUsers(res.data);
    } catch (e) { message.error('获取用户列表失败'); }
  };

  const handleSearch = () => {
    fetchUsers(searchKeyword);
  };

  const handleSearchKeyDown = (e) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  const fetchChatLogs = async () => {
    try {
      const res = await api.get('/admin/chat-logs');
      setChatLogs(res.data);
    } catch (e) { message.error('获取聊天记录失败'); }
  };

  const toggleUserStatus = async (userId, checked) => {
    try {
      await api.put(`/admin/users/${userId}/status?is_active=${checked}`);
      message.success('用户状态已更新');
      fetchUsers();
    } catch (e) { message.error('更新状态失败'); }
  };

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  const navItems = [
    { key: 'users', label: '用户管理', icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke="currentColor" strokeWidth="2"/><circle cx="9" cy="7" r="4" stroke="currentColor" strokeWidth="2"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" stroke="currentColor" strokeWidth="2"/></svg> },
    { key: 'chat', label: '聊天信息', icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" stroke="currentColor" strokeWidth="2"/></svg> },
    { key: 'models', label: '大模型管理', icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2"/><path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="currentColor" strokeWidth="2"/></svg> },
    { key: 'tools', label: '工具管理', icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z" stroke="currentColor" strokeWidth="2"/></svg> },
    { key: 'agents', label: '数字员工管理', icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" strokeWidth="2"/></svg> },
    { key: 'analytics', label: '数据分析', icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><line x1="18" y1="20" x2="18" y2="10" stroke="currentColor" strokeWidth="2"/><line x1="12" y1="20" x2="12" y2="4" stroke="currentColor" strokeWidth="2"/><line x1="6" y1="20" x2="6" y2="14" stroke="currentColor" strokeWidth="2"/></svg> },
  ];

  const renderContent = () => {
    if (activeNav === 'users') {
      return (
        <div className="ad-content-wrap">
          <div className="ad-page-header">
            <div>
              <h2 className="ad-page-title">用户管理</h2>
              <p className="ad-page-sub">监控和管理及摩擦能平台的所有注册用户及权限与状态。</p>
            </div>
            <button className="ad-btn-primary">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M16 21v-2a4 4 0 00-4-4H6a4 4 0 00-4 4v2" stroke="currentColor" strokeWidth="2"/><circle cx="9" cy="7" r="4" stroke="currentColor" strokeWidth="2"/><line x1="19" y1="8" x2="19" y2="14" stroke="currentColor" strokeWidth="2"/><line x1="22" y1="11" x2="16" y2="11" stroke="currentColor" strokeWidth="2"/></svg>
              添加新用户
            </button>
          </div>

          <div className="ad-toolbar">
            <div className="ad-search-box">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="11" cy="11" r="8" stroke="#9ca3af" strokeWidth="2"/><path d="M21 21l-4.35-4.35" stroke="#9ca3af" strokeWidth="2"/></svg>
              <input 
                placeholder="搜索用户名、邮箱..." 
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                onKeyDown={handleSearchKeyDown}
              />
            </div>
            <button className="ad-btn-ghost" onClick={handleSearch}>搜索</button>
            <button className="ad-btn-ghost" onClick={() => { setSearchKeyword(''); fetchUsers(''); }}>重置</button>
          </div>

          <div className="ad-table-wrap">
            <table className="ad-table">
              <thead>
                <tr>
                  <th>用户信息</th>
                  <th>邮箱地址</th>
                  <th>注册时间</th>
                  <th>账号状态</th>
                  <th>管理操作</th>
                </tr>
              </thead>
              <tbody>
                {users.map(u => (
                  <tr key={u.id}>
                    <td>
                      <div className="ad-user-cell">
                        <div className="ad-user-avatar">{u.username?.[0]?.toUpperCase() || 'U'}</div>
                        <div>
                          <div className="ad-user-name">{u.username}</div>
                          <div className="ad-user-id">ID: {u.id}</div>
                        </div>
                      </div>
                    </td>
                    <td>{u.email}</td>
                    <td>2023-11-20 14:20</td>
                    <td>
                      <span className={`ad-status-tag ${u.is_active ? 'ad-status-active' : 'ad-status-inactive'}`}>
                        {u.is_active ? '正常' : '已封禁'}
                      </span>
                    </td>
                    <td>
                      <div className="ad-actions">
                        <button className="ad-icon-btn" title="查看详情">
                          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" stroke="currentColor" strokeWidth="2"/><circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2"/></svg>
                        </button>
                        <button className="ad-icon-btn" title={u.is_active ? '封禁' : '解封'}>
                          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07" stroke="currentColor" strokeWidth="2"/></svg>
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div className="ad-pagination">
              <span>显示第 1 到 4 条，共 128 条记录</span>
              <div className="ad-page-btns">
                <button>1</button>
                <button>2</button>
                <button>3</button>
                <button>12</button>
              </div>
            </div>
          </div>
        </div>
      );
    }

    if (activeNav === 'chat') {
      return (
        <div className="ad-content-wrap">
          <div className="ad-page-header">
            <div>
              <h2 className="ad-page-title">聊天信息管理</h2>
              <p className="ad-page-sub">实时监控对话内容，识别风险信息并进行AI分析。</p>
            </div>
          </div>

          <div className="ad-chat-grid">
            <div className="ad-chat-main">
              <div className="ad-toolbar">
                <div className="ad-search-box">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="11" cy="11" r="8" stroke="#9ca3af" strokeWidth="2"/><path d="M21 21l-4.35-4.35" stroke="#9ca3af" strokeWidth="2"/></svg>
                  <input placeholder="搜索对话内容或用户..." />
                </div>
                <select className="ad-filter">
                  <option>所有风险等级</option>
                  <option>正常</option>
                  <option>中等</option>
                  <option>高风险</option>
                </select>
              </div>

              <div className="ad-chat-list">
                {[
                  { id: 1, user: '张三', room: '技术讨论组', msg: '这个功能怎么实现？', risk: 'low', time: '2分钟前' },
                  { id: 2, user: '李四', room: '产品需求', msg: '需要添加新的支付方式', risk: 'low', time: '5分钟前' },
                  { id: 3, user: '王五', room: '客户支持', msg: '账号无法登录', risk: 'medium', time: '10分钟前' },
                  { id: 4, user: '赵六', room: '市场推广', msg: '活动效果不错', risk: 'low', time: '15分钟前' },
                ].map(chat => (
                  <div key={chat.id} className="ad-chat-item">
                    <div className="ad-chat-item-header">
                      <div className="ad-chat-user">
                        <div className="ad-chat-avatar">{chat.user[0]}</div>
                        <div>
                          <div className="ad-chat-username">{chat.user}</div>
                          <div className="ad-chat-room">{chat.room}</div>
                        </div>
                      </div>
                      <span className={`ad-risk-tag ad-risk-${chat.risk}`}>
                        {chat.risk === 'low' ? '正常' : chat.risk === 'medium' ? '中等' : '高风险'}
                      </span>
                    </div>
                    <div className="ad-chat-msg">{chat.msg}</div>
                    <div className="ad-chat-footer">
                      <span className="ad-chat-time">{chat.time}</span>
                      <div className="ad-chat-actions">
                        <button className="ad-btn-text">查看详情</button>
                        <button className="ad-btn-text">AI分析</button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div className="ad-chat-panel">
              <div className="ad-panel-card">
                <h3 className="ad-panel-title">实时监控</h3>
                <div className="ad-monitor-stats">
                  <div className="ad-monitor-item">
                    <div className="ad-monitor-label">今日消息</div>
                    <div className="ad-monitor-value">12,847</div>
                  </div>
                  <div className="ad-monitor-item">
                    <div className="ad-monitor-label">风险消息</div>
                    <div className="ad-monitor-value ad-text-red">23</div>
                  </div>
                  <div className="ad-monitor-item">
                    <div className="ad-monitor-label">活跃用户</div>
                    <div className="ad-monitor-value">1,284</div>
                  </div>
                </div>
              </div>

              <div className="ad-panel-card">
                <h3 className="ad-panel-title">AI 分析建议</h3>
                <div className="ad-ai-tips">
                  <div className="ad-ai-tip">
                    <div className="ad-ai-tip-icon">💡</div>
                    <div className="ad-ai-tip-text">检测到3条可疑对话，建议人工审核</div>
                  </div>
                  <div className="ad-ai-tip">
                    <div className="ad-ai-tip-icon">⚠️</div>
                    <div className="ad-ai-tip-text">用户"王五"频繁提及敏感词汇</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      );
    }

    if (activeNav === 'models') {
      return (
        <div className="ad-content-wrap">
          <div className="ad-page-header">
            <div>
              <h2 className="ad-page-title">大模型管理</h2>
              <p className="ad-page-sub">配置和管理AI大模型，监控使用情况和性能指标。</p>
            </div>
            <button className="ad-btn-primary">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" strokeWidth="2"/><line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" strokeWidth="2"/></svg>
              添加新模型
            </button>
          </div>

          <div className="ad-models-grid">
            {[
              { name: 'GPT-4', provider: 'OpenAI', status: 'active', calls: '128.4K', tokens: '45.2M' },
              { name: 'Claude 3', provider: 'Anthropic', status: 'active', calls: '89.2K', tokens: '32.1M' },
              { name: 'Gemini Pro', provider: 'Google', status: 'inactive', calls: '12.8K', tokens: '4.5M' },
              { name: 'LLaMA 2', provider: 'Meta', status: 'active', calls: '45.6K', tokens: '18.9M' },
            ].map((model, i) => (
              <div key={i} className="ad-model-card">
                <div className="ad-model-header">
                  <div className="ad-model-icon">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2"/><path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="currentColor" strokeWidth="2"/></svg>
                  </div>
                  <span className={`ad-model-status ${model.status === 'active' ? 'ad-status-active' : 'ad-status-inactive'}`}>
                    {model.status === 'active' ? '运行中' : '已停用'}
                  </span>
                </div>
                <h3 className="ad-model-name">{model.name}</h3>
                <div className="ad-model-provider">{model.provider}</div>
                <div className="ad-model-stats">
                  <div className="ad-model-stat">
                    <div className="ad-model-stat-label">调用次数</div>
                    <div className="ad-model-stat-value">{model.calls}</div>
                  </div>
                  <div className="ad-model-stat">
                    <div className="ad-model-stat-label">Token消耗</div>
                    <div className="ad-model-stat-value">{model.tokens}</div>
                  </div>
                </div>
                <div className="ad-model-actions">
                  <button className="ad-btn-ghost">配置</button>
                  <button className="ad-btn-ghost">测试</button>
                </div>
              </div>
            ))}
          </div>
        </div>
      );
    }

    if (activeNav === 'tools') {
      return (
        <div className="ad-content-wrap">
          <div className="ad-page-header">
            <div>
              <h2 className="ad-page-title">工具管理</h2>
              <p className="ad-page-sub">管理AI可调用的工具和API接口，配置权限和参数。</p>
            </div>
            <button className="ad-btn-primary">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" strokeWidth="2"/><line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" strokeWidth="2"/></svg>
              添加新工具
            </button>
          </div>

          <div className="ad-tools-grid">
            {[
              { name: '天气查询', category: 'API', status: 'active', calls: '2.4K', desc: '获取实时天气信息' },
              { name: '数据库查询', category: 'Database', status: 'active', calls: '8.9K', desc: '执行SQL查询操作' },
              { name: '文件上传', category: 'Storage', status: 'active', calls: '1.2K', desc: '上传文件到云存储' },
              { name: '邮件发送', category: 'Communication', status: 'inactive', calls: '456', desc: '发送电子邮件通知' },
              { name: '图片生成', category: 'AI', status: 'active', calls: '3.7K', desc: 'AI图片生成服务' },
              { name: '语音识别', category: 'AI', status: 'active', calls: '5.1K', desc: '语音转文字服务' },
            ].map((tool, i) => (
              <div key={i} className="ad-tool-card">
                <div className="ad-tool-header">
                  <div className="ad-tool-icon">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z" stroke="currentColor" strokeWidth="2"/></svg>
                  </div>
                  <span className="ad-tool-category">{tool.category}</span>
                </div>
                <h3 className="ad-tool-name">{tool.name}</h3>
                <p className="ad-tool-desc">{tool.desc}</p>
                <div className="ad-tool-footer">
                  <div className="ad-tool-calls">调用: {tool.calls}</div>
                  <span className={`ad-tool-status ${tool.status === 'active' ? 'ad-status-dot-green' : 'ad-status-dot-gray'}`} />
                </div>
              </div>
            ))}
          </div>
        </div>
      );
    }

    if (activeNav === 'agents') {
      return (
        <div className="ad-content-wrap">
          <div className="ad-page-header">
            <div>
              <h2 className="ad-page-title">数字员工管理</h2>
              <p className="ad-page-sub">创建和管理AI Agent，配置其能力和工作流程。</p>
            </div>
            <button className="ad-btn-primary">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" strokeWidth="2"/><line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" strokeWidth="2"/></svg>
              创建新员工
            </button>
          </div>

          <div className="ad-agents-grid">
            {[
              { name: '客服助手', role: '客户支持', model: 'GPT-4', tools: 5, status: 'active', tasks: '1.2K' },
              { name: '数据分析师', role: '数据分析', model: 'Claude 3', tools: 8, status: 'active', tasks: '856' },
              { name: '内容创作者', role: '内容生成', model: 'GPT-4', tools: 3, status: 'active', tasks: '2.4K' },
              { name: '代码审查员', role: '代码审查', model: 'Claude 3', tools: 6, status: 'inactive', tasks: '342' },
            ].map((agent, i) => (
              <div key={i} className="ad-agent-card">
                <div className="ad-agent-header">
                  <div className="ad-agent-avatar">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" strokeWidth="2"/></svg>
                  </div>
                  <span className={`ad-agent-status ${agent.status === 'active' ? 'ad-status-active' : 'ad-status-inactive'}`}>
                    {agent.status === 'active' ? '在线' : '离线'}
                  </span>
                </div>
                <h3 className="ad-agent-name">{agent.name}</h3>
                <div className="ad-agent-role">{agent.role}</div>
                <div className="ad-agent-info">
                  <div className="ad-agent-info-item">
                    <span className="ad-agent-info-label">模型:</span>
                    <span className="ad-agent-info-value">{agent.model}</span>
                  </div>
                  <div className="ad-agent-info-item">
                    <span className="ad-agent-info-label">工具:</span>
                    <span className="ad-agent-info-value">{agent.tools}个</span>
                  </div>
                  <div className="ad-agent-info-item">
                    <span className="ad-agent-info-label">任务:</span>
                    <span className="ad-agent-info-value">{agent.tasks}</span>
                  </div>
                </div>
                <div className="ad-agent-actions">
                  <button className="ad-btn-ghost">配置</button>
                  <button className="ad-btn-ghost">查看</button>
                </div>
              </div>
            ))}
          </div>
        </div>
      );
    }

    if (activeNav === 'analytics') {
      const hourlyData = [
        { time: '00:00', value: 120 }, { time: '04:00', value: 80 }, { time: '08:00', value: 200 },
        { time: '12:00', value: 350 }, { time: '16:00', value: 280 }, { time: '20:00', value: 150 }, { time: '23:00', value: 100 }
      ];
      const pieData = [
        { name: '正常', value: 70 }, { name: '中等', value: 20 }, { name: '高风险', value: 10 }
      ];
      const COLORS = ['#4f46e5', '#06b6d4', '#ef4444'];

      return (
        <div className="ad-content-wrap">
          <div className="ad-page-header">
            <h2 className="ad-page-title">数据分析中心</h2>
            <p className="ad-page-sub">实时监控系统运行状况，为用户产品交互提供</p>
          </div>

          <div className="ad-stats-grid">
            <div className="ad-stat-card">
              <div className="ad-stat-icon ad-stat-icon-blue">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke="white" strokeWidth="2"/><circle cx="9" cy="7" r="4" stroke="white" strokeWidth="2"/></svg>
              </div>
              <div className="ad-stat-info">
                <div className="ad-stat-label">总用户数</div>
                <div className="ad-stat-value">1,284,502</div>
                <div className="ad-stat-trend ad-trend-up">+12.5%</div>
              </div>
            </div>
            <div className="ad-stat-card">
              <div className="ad-stat-icon ad-stat-icon-green">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" stroke="white" strokeWidth="2"/></svg>
              </div>
              <div className="ad-stat-info">
                <div className="ad-stat-label">活跃会话</div>
                <div className="ad-stat-value">42,910</div>
                <div className="ad-stat-trend ad-trend-up">+5.2%</div>
              </div>
            </div>
            <div className="ad-stat-card">
              <div className="ad-stat-icon ad-stat-icon-orange">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" stroke="white" strokeWidth="2"/><polyline points="12 6 12 12 16 14" stroke="white" strokeWidth="2"/></svg>
              </div>
              <div className="ad-stat-info">
                <div className="ad-stat-label">TOKEN 消耗总量</div>
                <div className="ad-stat-value">892.4M</div>
                <div className="ad-stat-trend ad-trend-down">-2.1%</div>
              </div>
            </div>
            <div className="ad-stat-card">
              <div className="ad-stat-icon ad-stat-icon-purple">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="white" strokeWidth="2"/></svg>
              </div>
              <div className="ad-stat-info">
                <div className="ad-stat-label">AI 响应准确率</div>
                <div className="ad-stat-value">98.42%</div>
                <div className="ad-stat-trend ad-trend-up">+0.8%</div>
              </div>
            </div>
          </div>

          <div className="ad-charts-row">
            <div className="ad-chart-card ad-chart-large">
              <div className="ad-chart-header">
                <h3>每小时对话量趋势</h3>
                <div className="ad-chart-tabs">
                  <button className="ad-chart-tab ad-chart-tab-active">24小时</button>
                  <button className="ad-chart-tab">7天</button>
                </div>
              </div>
              <ResponsiveContainer width="100%" height={240}>
                <LineChart data={hourlyData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                  <XAxis dataKey="time" stroke="#9ca3af" style={{ fontSize: 12 }} />
                  <YAxis stroke="#9ca3af" style={{ fontSize: 12 }} />
                  <Tooltip />
                  <Line type="monotone" dataKey="value" stroke="#4f46e5" strokeWidth={2} dot={{ fill: '#4f46e5', r: 4 }} />
                </LineChart>
              </ResponsiveContainer>
            </div>

            <div className="ad-chart-card">
              <div className="ad-chart-header">
                <h3>信息分布预测</h3>
              </div>
              <ResponsiveContainer width="100%" height={200}>
                <PieChart>
                  <Pie data={pieData} cx="50%" cy="50%" innerRadius={50} outerRadius={80} dataKey="value" label>
                    {pieData.map((entry, index) => <Cell key={`cell-${index}`} fill={COLORS[index]} />)}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
              <div className="ad-pie-legend">
                {pieData.map((d, i) => (
                  <div key={i} className="ad-legend-item">
                    <span className="ad-legend-dot" style={{ background: COLORS[i] }} />
                    <span>{d.name} ({d.value}%)</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      );
    }

    return (
      <div className="ad-placeholder">
        <svg width="48" height="48" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" stroke="#d1d5db" strokeWidth="1.5"/><path d="M12 8v4M12 16h.01" stroke="#d1d5db" strokeWidth="2"/></svg>
        <div className="ad-placeholder-title">{navItems.find(n => n.key === activeNav)?.label}</div>
        <div className="ad-placeholder-sub">该功能正在开发中，敬请期待</div>
      </div>
    );
  };

  return (
    <div className="ad-root">
      {/* 左侧导航 */}
      <aside className="ad-sidebar">
        <div className="ad-logo">
          <div className="ad-logo-icon">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" stroke="white" strokeWidth="2"/></svg>
          </div>
          <div>
            <div className="ad-logo-text">灵犀智能</div>
            <div className="ad-logo-sub">管理中心</div>
          </div>
        </div>

        <nav className="ad-nav">
          {navItems.map(item => (
            <button
              key={item.key}
              className={`ad-nav-item ${activeNav === item.key ? 'ad-nav-active' : ''}`}
              onClick={() => { setActiveNav(item.key); if (item.key === 'users') fetchUsers(); if (item.key === 'chat') fetchChatLogs(); }}
            >
              <span className="ad-nav-icon">{item.icon}</span>
              {item.label}
            </button>
          ))}
        </nav>

        <div className="ad-sidebar-footer">
          <button className="ad-nav-item" onClick={() => {}}>
            <span className="ad-nav-icon">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2"/><path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="currentColor" strokeWidth="2"/></svg>
            </span>
            个人设置
          </button>
          <button className="ad-nav-item" onClick={() => {}}>
            <span className="ad-nav-icon">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2"/><path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="currentColor" strokeWidth="2"/></svg>
            </span>
            系统设置
          </button>
        </div>
      </aside>

      {/* 主内容 */}
      <main className="ad-main">
        {/* 顶部栏 */}
        <header className="ad-topbar">
          <div className="ad-breadcrumb">
            <span>管理控制台</span>
            <span>/</span>
            <span>{navItems.find(n => n.key === activeNav)?.label}</span>
          </div>
          <div className="ad-topbar-right">
            <div className="ad-search-mini">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="11" cy="11" r="8" stroke="#9ca3af" strokeWidth="2"/><path d="M21 21l-4.35-4.35" stroke="#9ca3af" strokeWidth="2"/></svg>
              <input placeholder="搜索模型或资源..." />
            </div>
            <button className="ad-icon-btn-top">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 01-3.46 0" stroke="currentColor" strokeWidth="2"/></svg>
              <span className="ad-badge">3</span>
            </button>
            <button className="ad-icon-btn-top">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2"/><path d="M9.09 9a3 3 0 015.83 1c0 2-3 3-3 3M12 17h.01" stroke="currentColor" strokeWidth="2"/></svg>
            </button>
            <div className="ad-user-menu">
              <div className="ad-user-avatar-top">{user?.username?.[0]?.toUpperCase() || 'A'}</div>
              <span>Admin</span>
            </div>
          </div>
        </header>

        {/* 内容区 */}
        <div className="ad-content">
          {renderContent()}
        </div>
      </main>
    </div>
  );
};

export default AdminDashboard;
