import { useState, useEffect, useCallback } from 'react';
import { listAdminSessions, listActiveSessions, listClients, setClientNote } from '@/api/admin';
import type { SessionState, ClientInfo } from '@/types/admin';

type TabId = 'sessions' | 'clients';

export function AdminDashboard() {
  const [tab, setTab] = useState<TabId>('sessions');

  return (
    <div className="h-full flex flex-col bg-[#FFFAF5] dark:bg-[#1a1a2e]">
      <div className="flex-shrink-0 px-6 py-4 border-b border-pink-100 dark:border-pink-900">
        <h2 className="text-lg font-semibold text-gray-800 dark:text-gray-200">管理仪表盘</h2>
        <p className="text-xs text-gray-400 mt-1">会话与客户端概览</p>
      </div>

      <div className="flex-shrink-0 flex border-b border-pink-100 dark:border-pink-900 px-6">
        {([
          ['sessions', '活跃会话'],
          ['clients', '已知客户端'],
        ] as [TabId, string][]).map(([id, label]) => (
          <button
            key={id}
            onClick={() => setTab(id)}
            className={`px-4 py-2.5 text-sm font-medium transition-colors border-b-2 -mb-px ${
              tab === id
                ? 'text-pink-500 border-pink-500'
                : 'text-gray-400 border-transparent hover:text-gray-600'
            }`}
          >
            {label}
          </button>
        ))}
      </div>

      <div className="flex-1 overflow-y-auto p-6">
        {tab === 'sessions' && <SessionsTab />}
        {tab === 'clients' && <ClientsTab />}
      </div>
    </div>
  );
}

// ========== Sessions Tab ==========

function SessionsTab() {
  const [sessions, setSessions] = useState<SessionState[]>([]);
  const [activeUsers, setActiveUsers] = useState<Record<string, SessionState[]>>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    const [allRes, activeRes] = await Promise.all([listAdminSessions(), listActiveSessions()]);
    if (allRes.data?.sessions) setSessions(allRes.data.sessions);
    else if (allRes.error) setError(allRes.error);
    if (activeRes.data?.users) setActiveUsers(activeRes.data.users);
    setLoading(false);
  }, []);

  useEffect(() => { load(); }, [load]);

  if (loading) return <div className="text-sm text-gray-400">加载中...</div>;

  const totalMessages = sessions.reduce((sum, s) => sum + (s.message_count || 0), 0);

  return (
    <div className="space-y-4">
      {error && (
        <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-500">
          {error}
        </div>
      )}

      {/* Stats */}
      <div className="grid grid-cols-3 gap-3">
        <div className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-pink-100 dark:border-pink-900 text-center">
          <p className="text-2xl font-bold text-pink-500">{sessions.length}</p>
          <p className="text-xs text-gray-400 mt-1">总会话</p>
        </div>
        <div className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-pink-100 dark:border-pink-900 text-center">
          <p className="text-2xl font-bold text-green-500">{Object.keys(activeUsers).length}</p>
          <p className="text-xs text-gray-400 mt-1">活跃用户</p>
        </div>
        <div className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-pink-100 dark:border-pink-900 text-center">
          <p className="text-2xl font-bold text-blue-500">{totalMessages}</p>
          <p className="text-xs text-gray-400 mt-1">总消息</p>
        </div>
      </div>

      {/* All Sessions */}
      <div>
        <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">所有会话 ({sessions.length})</h4>
        <div className="space-y-2">
          {sessions.slice(0, 50).map((s) => (
            <div key={s.session_id} className="p-3 bg-white dark:bg-gray-800 rounded-lg border border-pink-100 dark:border-pink-900 flex items-center justify-between">
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <span className="text-sm font-medium text-gray-700 dark:text-gray-300 truncate">
                    {s.is_main ? '🏠 ' : ''}{s.title || '未命名'}
                  </span>
                  {s.is_main && <span className="px-1.5 py-0.5 text-[10px] bg-amber-100 text-amber-600 rounded">主对话</span>}
                </div>
                <p className="text-xs text-gray-400 mt-0.5">
                  {s.user_id} · {s.message_count || 0} 条消息
                </p>
              </div>
              <span className="text-[10px] text-gray-400 ml-2 flex-shrink-0">
                {new Date(s.updated_at).toLocaleString('zh-CN')}
              </span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ========== Clients Tab ==========

function ClientsTab() {
  const [clients, setClients] = useState<ClientInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [editingNote, setEditingNote] = useState<{ id: string; note: string } | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    const res = await listClients();
    if (res.data?.clients) setClients(res.data.clients);
    else if (res.error) setError(res.error);
    setLoading(false);
  }, []);

  useEffect(() => { load(); }, [load]);

  const handleSaveNote = async () => {
    if (!editingNote) return;
    const res = await setClientNote(editingNote.id, editingNote.note);
    if (res.error) setError(res.error);
    else { setEditingNote(null); await load(); }
  };

  if (loading) return <div className="text-sm text-gray-400">加载中...</div>;

  const onlineCount = clients.filter((c) => c.online).length;

  return (
    <div className="space-y-4">
      {error && (
        <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-500">
          {error}
        </div>
      )}

      <div className="flex items-center gap-3">
        <span className="text-xs text-gray-400">{clients.length} 个客户端 ({onlineCount} 在线)</span>
        <button onClick={load} className="text-xs text-pink-500 hover:text-pink-600">刷新</button>
      </div>

      <div className="space-y-2">
        {clients.map((c) => (
          <div key={c.client_id} className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-pink-100 dark:border-pink-900">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3 min-w-0 flex-1">
                <span className={`w-2.5 h-2.5 rounded-full flex-shrink-0 ${c.online ? 'bg-green-400' : 'bg-gray-300'}`} />
                <div className="min-w-0">
                  <p className="text-sm font-medium text-gray-700 dark:text-gray-300 truncate">
                    {c.device_name || c.client_id}
                  </p>
                  <p className="text-xs text-gray-400 mt-0.5 font-mono">{c.client_id}</p>
                  {c.user_agent && (
                    <p className="text-xs text-gray-400 truncate mt-0.5">{c.user_agent}</p>
                  )}
                  {c.note && (
                    <p className="text-xs text-amber-500 mt-0.5">备注: {c.note}</p>
                  )}
                </div>
              </div>
              <div className="flex items-center gap-2 ml-3">
                {c.last_seen && (
                  <span className="text-[10px] text-gray-400">{new Date(c.last_seen).toLocaleString('zh-CN')}</span>
                )}
                <button
                  onClick={() => setEditingNote({ id: c.client_id, note: c.note || '' })}
                  className="px-2 py-1 text-xs text-amber-500 hover:bg-amber-50 dark:hover:bg-amber-900/20 rounded transition-colors"
                >
                  备注
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Note Edit Modal */}
      {editingNote && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6 m-4 max-w-sm w-full border border-pink-100 dark:border-pink-700">
            <h3 className="text-lg font-semibold text-gray-800 dark:text-gray-200 mb-3">设置备注</h3>
            <p className="text-xs text-gray-400 mb-3 font-mono">{editingNote.id}</p>
            <input
              type="text" value={editingNote.note}
              onChange={(e) => setEditingNote({ ...editingNote, note: e.target.value })}
              className="w-full px-3 py-2 rounded-lg border border-pink-200 dark:border-pink-700 bg-white dark:bg-gray-700 text-sm"
              placeholder="输入备注..."
              onKeyDown={(e) => e.key === 'Enter' && handleSaveNote()}
            />
            <div className="flex justify-end gap-3 mt-4">
              <button onClick={() => setEditingNote(null)}
                className="px-4 py-2 rounded-lg text-sm text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700">取消</button>
              <button onClick={handleSaveNote}
                className="px-4 py-2 rounded-lg text-sm bg-pink-400 hover:bg-pink-500 text-white font-medium">保存</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
