import { useEffect, useState } from 'react';
import { useStore, TAB_DEFS, startPolling, stopPolling, startSSE, stopSSE, isEdict, isArchived } from './store';
import { api } from './api';
import EdictBoard from './components/EdictBoard';
import MailPanel from './components/MailPanel';
import MonitorPanel from './components/MonitorPanel';
import OfficialPanel from './components/OfficialPanel';
import ModelConfig from './components/ModelConfig';
import SkillsConfig from './components/SkillsConfig';
import SessionsPanel from './components/SessionsPanel';
import MorningPanel from './components/MorningPanel';
import MemorialPanel from './components/MemorialPanel';
import TemplatePanel from './components/TemplatePanel';
import TaskModal from './components/TaskModal';
import Toaster from './components/Toaster';
import CourtCeremony from './components/CourtCeremony';
import CourtDiscussion from './components/CourtDiscussion';
import UsagePanel from './components/UsagePanel';
import SettingsPanel from './components/SettingsPanel';
import GlobalSearch from './components/GlobalSearch';
import NotificationCenter from './components/NotificationCenter';

export default function App() {
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showNotifCenter, setShowNotifCenter] = useState(false);
  const [showSearch, setShowSearch] = useState(false);
  const activeTab = useStore((s) => s.activeTab);
  const setActiveTab = useStore((s) => s.setActiveTab);
  const liveStatus = useStore((s) => s.liveStatus);
  const countdown = useStore((s) => s.countdown);
  const loadAll = useStore((s) => s.loadAll);
  const toast = useStore((s) => s.toast);
  const projects = useStore((s) => s.projects);
  const selectedProjectId = useStore((s) => s.selectedProjectId);
  const setSelectedProjectId = useStore((s) => s.setSelectedProjectId);
  const v2tasksLoading = useStore((s) => s.v2tasksLoading);
  const notifUnread = ((useStore((s) => s.sseEvents) || []) as any[]).filter((n: any) => !n.read).length;

  useEffect(() => {
    startPolling();
    startSSE();
    // P1: 活跃度追踪
    const onActivity = () => { (window as any).__markActivity?.(); };
    window.addEventListener('mousemove', onActivity);
    window.addEventListener('keydown', onActivity);
    window.addEventListener('click', onActivity);
    return () => {
      stopPolling();
      stopSSE();
      window.removeEventListener('mousemove', onActivity);
      window.removeEventListener('keydown', onActivity);
      window.removeEventListener('click', onActivity);
    };
  }, []);

  // ⌘K / Ctrl+K 全局搜索
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setShowSearch(true);
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, []);

  const tasks = liveStatus?.tasks || [];
  const moziTasks = tasks.filter(isEdict);
  const activeTasks = moziTasks.filter((t) => !isArchived(t));
  const syncOk = !!liveStatus;

  const tabBadge = (key: string): string => {
    if (key === 'tasks') return String(activeTasks.length);
    if (key === 'sessions') return String(tasks.filter((t) => !isEdict(t)).length);
    if (key === 'archives') return String(moziTasks.filter((t) => ['completed', 'cancelled'].includes(t.state)).length);
    if (key === 'monitor') {
      const executing = tasks.filter((t) => isEdict(t) && t.state === 'executing').length;
      return executing + '活跃';
    }
    if (key === 'mail') {
      const unread = useStore.getState().mailUnread || 0;
      return unread > 0 ? String(unread) : '';
    }
    return '';
  };

  // Tab → Component mapping (moziplus keys → Edict components)
  const panels: Record<string, React.ReactNode> = {
    tasks: <EdictBoard />,
    mail: <MailPanel />,
    court: <CourtDiscussion />,
    monitor: <MonitorPanel />,
    agents: <OfficialPanel />,
    models: <ModelConfig />,
    skills: <SkillsConfig />,
    sessions: <SessionsPanel />,
    archives: <MemorialPanel />,
    templates: <TemplatePanel />,
    usage: <UsagePanel />,
    morning: <MorningPanel />,
    settings: <SettingsPanel />,
  };

  return (
    <div className="wrap">
      {/* Header */}
      <div className="hdr">
        <div>
          <div className="logo">三国 · 墨攻</div>
          <div className="sub-text">MoziPlus Dashboard v2.0</div>
        </div>
        <div className="hdr-r">
          <span className={`chip ${syncOk ? 'ok' : syncOk === false ? 'err' : ''}`}>
            {syncOk ? '✅ 同步正常' : syncOk === false ? '❌ 服务器未启动' : '⏳ 连接中…'}
          </span>
          <span className="chip">{activeTasks.length} 个任务</span>
          {/* 通知中心 */}
          <button className="chip" style={{ cursor: 'pointer', border: '1px solid var(--line)', position: 'relative' }} title="通知中心" onClick={() => setShowNotifCenter(true)}>
            🔔
            {notifUnread > 0 && (
              <span style={{ position: 'absolute', top: -4, right: -4, fontSize: 9, background: '#ff5270', color: '#fff', borderRadius: 8, padding: '0 4px', fontWeight: 700, lineHeight: '16px' }}>{notifUnread > 99 ? '99+' : notifUnread}</span>
            )}
          </button>
          {showNotifCenter && <NotificationCenter onClose={() => setShowNotifCenter(false)} />}
          <button
            className="btn btn-action"
            style={{ fontSize: 12, padding: '4px 14px', marginLeft: 6 }}
            onClick={() => setShowCreateModal(true)}
          >
            📜 新建军令
          </button>
          <button
            onClick={() => { loadAll(); toast('已刷新'); }}
            style={{
              fontSize: 11, padding: '2px 8px', borderRadius: 4,
              border: '1px solid var(--line)', background: 'var(--panel)',
              color: 'var(--fg)', cursor: 'pointer', marginLeft: 6,
            }}
            title="手动刷新"
          >{v2tasksLoading ? '⟳ ...' : '⟳ 刷新'}</button>
        </div>
      </div>

      {/* Tabs */}
      <div className="tabs">
        {TAB_DEFS.map((t) => (
          <div
            key={t.key}
            className={`tab ${activeTab === t.key ? 'active' : ''}`}
            onClick={() => setActiveTab(t.key)}
          >
            {t.icon} {t.label}
            {tabBadge(t.key) && <span className="tbadge">{tabBadge(t.key)}</span>}
          </div>
        ))}
      </div>

      {/* Panel */}
      {panels[activeTab] || null}

      {/* Create Task Modal */}
      {showCreateModal && <CreateTaskModal
        onClose={() => setShowCreateModal(false)}
        onSubmit={async (data) => {
          try {
            const r = await api.createTask({...data, title: data.title || ''});
            const rAny = r as unknown as Record<string, unknown>;
            if (r.ok || r.taskId || rAny.id) {
              const tid = r.taskId || String(rAny.id || '');
              toast(`📜 ${tid} 军令已创建`, 'ok');
              setShowCreateModal(false);
              loadAll();
            } else {
              toast(r.error || '创建失败', 'err');
            }
          } catch (e: any) {
            toast(e.message || '⚠️ 创建失败', 'err');
          }
        }}
      />}

      {/* Overlays */}
      <TaskModal />
      <Toaster />
      <CourtCeremony />
      {showSearch && <GlobalSearch onClose={() => setShowSearch(false)} />}
    </div>
  );
}

/* ── Create Task Modal ── */
function CreateTaskModal({ onClose, onSubmit }: {
  onClose: () => void;
  onSubmit: (data: { requirement: string; project_root: string; project_type: string; title?: string }) => Promise<void>;
}) {
  const projects = useStore(s => s.projects);
  const selectedProjectId = useStore(s => s.selectedProjectId);
  const [requirement, setRequirement] = useState('');
  const [title, setTitle] = useState('');
  const [projectId, setProjectId] = useState(selectedProjectId || '');
  const [loading, setLoading] = useState(false);

  const handleSubmit = () => {
    if (!requirement.trim()) return;
    setLoading(true);
    onSubmit({
      requirement: requirement.trim(),
      title: title.trim() || undefined,
      project_root: projectId || '/tmp',
      project_type: projectId || 'general',
    }).finally(() => setLoading(false));
  };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
      onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div style={{ background: 'var(--bg)', borderRadius: 12, padding: 24, width: 480, maxWidth: '90vw', boxShadow: '0 8px 32px rgba(0,0,0,0.3)', border: '1px solid var(--line)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <span style={{ fontSize: 16, fontWeight: 700 }}>📜 新建军令</span>
          <button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--muted)', cursor: 'pointer', fontSize: 18 }}>✕</button>
        </div>

        {/* Title */}
        <div style={{ marginBottom: 12 }}>
          <label style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 4, display: 'block' }}>标题（可选，不填将自动生成）</label>
          <input value={title} onChange={(e) => setTitle(e.target.value)}
            placeholder="简要概括任务，不填自动从描述生成..."
            style={{ width: '100%', padding: '8px 12px', borderRadius: 6, border: '1px solid var(--line)', background: 'var(--panel)', color: 'var(--fg)', fontSize: 13 }} />
        </div>

        {/* Requirement */}
        <div style={{ marginBottom: 12 }}>
          <label style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 4, display: 'block' }}>需求描述 <span style={{ color: '#ff5270' }}>*</span></label>
          <textarea value={requirement} onChange={(e) => setRequirement(e.target.value)} rows={4}
            placeholder="详细描述任务需求..."
            style={{ width: '100%', padding: '8px 12px', borderRadius: 6, border: '1px solid var(--line)', background: 'var(--panel)', color: 'var(--fg)', fontSize: 13, resize: 'vertical' }} />
        </div>

        {/* 项目选择 */}
        <div style={{ marginBottom: 16 }}>
          <label style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 4, display: 'block' }}>归属项目</label>
          <select value={projectId} onChange={(e) => setProjectId(e.target.value)}
            style={{ padding: '6px 10px', borderRadius: 6, border: '1px solid var(--line)', background: 'var(--panel)', color: 'var(--fg)', fontSize: 13, width: '100%' }}>
            <option value="_general">📝 一般任务（无归属）</option>
            {Object.entries(projects).filter(([pid]) => !pid.startsWith('_')).map(([pid, info]: [string, any]) => (
              <option key={pid} value={pid}>📁 {info.name || pid}</option>
            ))}
          </select>
        </div>

        {/* Actions */}
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button onClick={onClose} disabled={loading}
            style={{ padding: '6px 16px', borderRadius: 6, border: '1px solid var(--line)', background: 'var(--panel)', color: 'var(--fg)', cursor: 'pointer', fontSize: 13 }}>取消</button>
          <button onClick={handleSubmit} disabled={loading || !requirement.trim()}
            style={{ padding: '6px 16px', borderRadius: 6, border: 'none', background: requirement.trim() ? '#4a90d9' : '#555', color: '#fff', cursor: requirement.trim() ? 'pointer' : 'not-allowed', fontSize: 13, fontWeight: 600 }}>
            {loading ? '创建中...' : '发布军令'}
          </button>
        </div>
      </div>
    </div>
  );
}
