import { useEffect, useMemo, useRef, useState } from 'react';
import { Modal, Input, Spin, Empty, Tag } from 'antd';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import { SearchAPI, GlobalSearchResult } from '../api';

interface Props {
  open: boolean;
  onClose: () => void;
}

type FlatItem =
  | { kind: 'agent'; id: string; title: string; subtitle: string; route: string }
  | { kind: 'session'; id: string; agentId: string; title: string; subtitle: string; archived: boolean; route: string }
  | { kind: 'message'; id: string; agentId: string; sessionId: string; title: string; snippet: string; role: 'user' | 'assistant'; createdAt: number; route: string };

export default function CommandPalette({ open, onClose }: Props) {
  const [q, setQ] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<GlobalSearchResult | null>(null);
  const [active, setActive] = useState(0);
  const navigate = useNavigate();
  const inputRef = useRef<any>(null);

  // 重置
  useEffect(() => {
    if (open) {
      setQ('');
      setResult(null);
      setActive(0);
      setTimeout(() => inputRef.current?.focus(), 50);
    }
  }, [open]);

  // 防抖搜索
  useEffect(() => {
    const query = q.trim();
    if (!query) {
      setResult(null);
      return;
    }
    const t = setTimeout(async () => {
      setLoading(true);
      try {
        const r = await SearchAPI.global(query, 6);
        setResult(r);
        setActive(0);
      } catch {
        setResult({ agents: [], sessions: [], messages: [] });
      } finally {
        setLoading(false);
      }
    }, 200);
    return () => clearTimeout(t);
  }, [q]);

  const flat = useMemo<FlatItem[]>(() => {
    if (!result) return [];
    const list: FlatItem[] = [];
    for (const a of result.agents) {
      list.push({
        kind: 'agent',
        id: a.id,
        title: a.name,
        subtitle: a.description || a.model,
        route: `/agents/${a.id}/chat`
      });
    }
    for (const s of result.sessions) {
      list.push({
        kind: 'session',
        id: s.id,
        agentId: s.agentId,
        title: s.title,
        subtitle: `${s.agentName} · ${dayjs(s.updatedAt).format('MM-DD HH:mm')}`,
        archived: s.archived,
        route: `/agents/${s.agentId}/chat?session=${s.id}`
      });
    }
    for (const m of result.messages) {
      list.push({
        kind: 'message',
        id: m.id,
        agentId: m.agentId,
        sessionId: m.sessionId,
        title: `${m.agentName} / ${m.sessionTitle}`,
        snippet: m.snippet,
        role: m.role,
        createdAt: m.createdAt,
        route: `/agents/${m.agentId}/chat?session=${m.sessionId}&msg=${m.id}`
      });
    }
    return list;
  }, [result]);

  const handlePick = (it: FlatItem) => {
    navigate(it.route);
    onClose();
  };

  const onKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setActive((i) => Math.min(flat.length - 1, i + 1));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setActive((i) => Math.max(0, i - 1));
    } else if (e.key === 'Enter') {
      e.preventDefault();
      const it = flat[active];
      if (it) handlePick(it);
    } else if (e.key === 'Escape') {
      onClose();
    }
  };

  return (
    <Modal
      open={open}
      onCancel={onClose}
      footer={null}
      width={640}
      closable={false}
      destroyOnHidden
      styles={{ body: { padding: 0 }, content: { padding: 0, overflow: 'hidden' } }}
      style={{ top: 80 }}
    >
      <div style={{ padding: 12, borderBottom: '1px solid #f0f0f0' }}>
        <Input
          ref={inputRef}
          size="large"
          variant="borderless"
          placeholder="搜索智能体、会话、消息…  （↑↓ 切换 · Enter 跳转 · Esc 关闭）"
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onKeyDown={onKeyDown}
          prefix={<span style={{ color: '#9ca3af' }}>⌘K</span>}
        />
      </div>
      <div style={{ maxHeight: 440, overflow: 'auto' }}>
        {loading && (
          <div style={{ padding: 24, textAlign: 'center' }}>
            <Spin size="small" />
          </div>
        )}
        {!loading && q.trim() && flat.length === 0 && (
          <Empty
            description={`未找到与 "${q.trim()}" 相关的内容`}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            style={{ padding: 32 }}
          />
        )}
        {!loading && !q.trim() && (
          <div style={{ padding: 24, color: '#9ca3af', fontSize: 13 }}>
            <div style={{ marginBottom: 8 }}>💡 快捷键提示：</div>
            <ul style={{ paddingLeft: 18, margin: 0, lineHeight: 1.8 }}>
              <li><kbd>Ctrl/⌘ + K</kbd> 打开命令面板</li>
              <li><kbd>↑ ↓</kbd> 切换结果，<kbd>Enter</kbd> 跳转</li>
              <li>支持搜索：智能体名 / 会话标题 / 消息内容</li>
            </ul>
          </div>
        )}
        {!loading && flat.length > 0 && (
          <div>
            {(() => {
              const groups: { label: string; items: FlatItem[] }[] = [];
              const agents = flat.filter((x) => x.kind === 'agent');
              const sessions = flat.filter((x) => x.kind === 'session');
              const messages = flat.filter((x) => x.kind === 'message');
              if (agents.length) groups.push({ label: '🤖 智能体', items: agents });
              if (sessions.length) groups.push({ label: '💬 会话', items: sessions });
              if (messages.length) groups.push({ label: '📝 消息', items: messages });
              let cursor = 0;
              return groups.map((g) => (
                <div key={g.label}>
                  <div style={{ padding: '6px 14px', fontSize: 11, color: '#9ca3af', background: '#fafafa' }}>
                    {g.label}
                  </div>
                  {g.items.map((it) => {
                    const idx = cursor++;
                    const isActive = idx === active;
                    return (
                      <div
                        key={it.kind + ':' + it.id}
                        onMouseEnter={() => setActive(idx)}
                        onClick={() => handlePick(it)}
                        style={{
                          padding: '8px 14px',
                          cursor: 'pointer',
                          background: isActive ? '#eef2ff' : 'transparent',
                          borderLeft: isActive ? '3px solid #6366f1' : '3px solid transparent'
                        }}
                      >
                        {it.kind === 'agent' && (
                          <>
                            <div style={{ fontSize: 13, fontWeight: 500, color: '#1f2330' }}>{it.title}</div>
                            <div style={{ fontSize: 11, color: '#6b7280', marginTop: 2 }}>{it.subtitle}</div>
                          </>
                        )}
                        {it.kind === 'session' && (
                          <>
                            <div style={{ fontSize: 13, color: '#1f2330' }}>
                              💬 {it.title}
                              {it.archived && <Tag style={{ marginLeft: 6 }}>归档</Tag>}
                            </div>
                            <div style={{ fontSize: 11, color: '#6b7280', marginTop: 2 }}>{it.subtitle}</div>
                          </>
                        )}
                        {it.kind === 'message' && (
                          <>
                            <div style={{ fontSize: 11, color: '#6b7280', marginBottom: 2 }}>
                              <span
                                style={{
                                  display: 'inline-block',
                                  background: it.role === 'user' ? '#e0e7ff' : '#d1fae5',
                                  color: it.role === 'user' ? '#4338ca' : '#065f46',
                                  padding: '0 4px',
                                  borderRadius: 3,
                                  marginRight: 6,
                                  fontSize: 10
                                }}
                              >
                                {it.role === 'user' ? '我' : 'AI'}
                              </span>
                              {it.title} · {dayjs(it.createdAt).format('MM-DD HH:mm')}
                            </div>
                            <div
                              style={{ fontSize: 12, color: '#374151', lineHeight: 1.4 }}
                              dangerouslySetInnerHTML={{ __html: it.snippet }}
                            />
                          </>
                        )}
                      </div>
                    );
                  })}
                </div>
              ));
            })()}
          </div>
        )}
      </div>
    </Modal>
  );
}
