import { useEffect, useState } from 'react';
import { useStore, DEPTS, isEdict, stateLabel } from '../store';
import { api, type OfficialInfo } from '../api';

// ── Agent name mapping (P1-08) ──

const AGENT_NAMES: Record<string, string> = {
  'zhangfei-dev': '张飞 翼德',
  'guanyu-dev': '关羽 云长',
  'zhaoyun-data': '赵云 子龙',
  'jiangwei-infra': '姜维 伯约',
  'simayi-challenger': '司马懿 仲达',
  'pangtong-fujunshi': '庞统 士元',
};

const AGENT_EMOJI: Record<string, string> = {
  'zhangfei-dev': '⚔️',
  'guanyu-dev': '🗡️',
  'zhaoyun-data': '🏹',
  'jiangwei-infra': '🛡️',
  'simayi-challenger': '🦅',
  'pangtong-fujunshi': '🐦',
};

const AGENT_DEPT: Record<string, string> = {
  'zhangfei-dev': '张飞',
  'guanyu-dev': '关羽',
  'zhaoyun-data': '赵云',
  'jiangwei-infra': '姜维',
  'simayi-challenger': '司马懿',
  'pangtong-fujunshi': '庞统',
};

// ── Stats card definitions (P1-09) ──

interface StatCardDef {
  icon: string;
  label: string;
  color: string;
  bg: string;
  border: string;
  states: string[];
}

const STAT_CARDS: StatCardDef[] = [
  { icon: '📋', label: '总任务', color: '#dde4f8', bg: '#0f1219', border: '#1c223688', states: ['__all__'] },
  { icon: '⚔️', label: '执行中', color: '#6a9eff', bg: '#0a1428', border: '#6a9eff44', states: ['executing', 'Doing'] },
  { icon: '✅', label: '已完成', color: '#2ecc8a', bg: '#0a2018', border: '#2ecc8a44', states: ['completed', 'Done'] },
  { icon: '⏳', label: '待审批', color: '#f5c842', bg: '#201a08', border: '#f5c84244', states: ['challenging', 'Review'] },
  { icon: '❌', label: '失败', color: '#ff5270', bg: '#200a10', border: '#ff527044', states: ['failed'] },
  { icon: '⏸️', label: '暂停', color: '#5a6b92', bg: '#141824', border: '#5a6b9244', states: ['paused'] },
];

export default function MonitorPanel() {
  const liveStatus = useStore((s) => s.liveStatus);
  const agentsStatusData = useStore((s) => s.agentsStatusData);
  const officialsData = useStore((s) => s.officialsData);
  const loadAgentsStatus = useStore((s) => s.loadAgentsStatus);
  const setModalTaskId = useStore((s) => s.setModalTaskId);
  const setActiveTab = useStore((s) => s.setActiveTab);
  const toast = useStore((s) => s.toast);

  // P3-11: engine scan state
  const [scanLoading, setScanLoading] = useState(false);
  const [scanResult, setScanResult] = useState<{ zombies: number; actions: { taskId: string; action: string; stalledSec?: number }[] } | null>(null);

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

  const tasks = liveStatus?.tasks || [];
  const allEdicts = tasks.filter((t) => isEdict(t));
  const activeTasks = allEdicts.filter((t) => t.state !== 'completed' && t.state !== 'Done' && t.state !== 'cancelled');

  // ── Compute stats ──
  function countStates(states: string[]): number {
    if (states.includes('__all__')) return allEdicts.length;
    return allEdicts.filter((t) => states.includes(t.state)).length;
  }

  // ── Build task lookup per dept ──
  const deptActiveTasks: Record<string, typeof activeTasks> = {};
  for (const t of activeTasks) {
    const dept = t.org || '';
    if (!deptActiveTasks[dept]) deptActiveTasks[dept] = [];
    deptActiveTasks[dept].push(t);
  }

  // Build official map
  const offMap: Record<string, OfficialInfo> = {};
  if (officialsData?.officials) {
    officialsData.officials.forEach((o) => { offMap[o.id] = o; });
  }

  // Agent wake
  const handleWake = async (agentId: string) => {
    try {
      const r = await api.agentWake(agentId);
      toast(r.message || '唤醒指令已发出');
      setTimeout(() => loadAgentsStatus(), 30000);
    } catch { toast('唤醒失败', 'err'); }
  };

  const handleWakeAll = async () => {
    if (!agentsStatusData) return;
    const toWake = agentsStatusData.agents.filter(
      (a) => a.id !== 'main' && a.status !== 'running' && a.status !== 'unconfigured'
    );
    if (!toWake.length) { toast('所有 Agent 均已在线'); return; }
    toast(`正在唤醒 ${toWake.length} 个 Agent...`);
    for (const a of toWake) {
      try { await api.agentWake(a.id); } catch { /* ignore */ }
    }
    toast(`${toWake.length} 个唤醒指令已发出，30秒后刷新状态`);
    setTimeout(() => loadAgentsStatus(), 30000);
  };

  // Click stat card → jump to tasks tab
  const handleStatClick = (card: StatCardDef) => {
    setActiveTab('tasks');
  };

  // P3-11: engine scan handler
  const handleSchedulerScan = async () => {
    setScanLoading(true);
    setScanResult(null);
    try {
      const r = await api.schedulerScan();
      const zombies = r.actions?.length || 0;
      setScanResult({ zombies, actions: (r.actions || []).map((a: any) => ({ taskId: a.taskId, action: a.action, stalledSec: a.stalledSec })) });
      toast(r.message || (zombies > 0 ? `发现 ${zombies} 个僵尸任务` : '一切正常'));
    } catch {
      toast('巡营扫描失败', 'err');
    } finally {
      setScanLoading(false);
    }
  };

  // P3-12: compute context pressure per agent from officialsData
  const contextPressureMap: Record<string, number> = {};
  if (officialsData?.officials) {
    for (const o of officialsData.officials) {
      const used = o.tokens_in + o.tokens_out;
      const pct = Math.min(100, Math.round((used / 200000) * 100));
      contextPressureMap[o.id] = pct;
    }
  }
  const avgPressure = Object.keys(contextPressureMap).length > 0
    ? Math.round(Object.values(contextPressureMap).reduce((a, b) => a + b, 0) / Object.keys(contextPressureMap).length)
    : 0;

  // Agent Status Panel data
  const asData = agentsStatusData;
  const filtered = asData?.agents?.filter((a) => a.id !== 'main') || [];
  const running = filtered.filter((a) => a.status === 'running').length;
  const idle = filtered.filter((a) => a.status === 'idle').length;
  const offline = filtered.filter((a) => a.status === 'offline').length;
  const unconf = filtered.filter((a) => a.status === 'unconfigured').length;
  const gw = asData?.gateway;
  const gwCls = gw?.probe ? 'ok' : gw?.alive ? 'warn' : 'err';

  return (
    <div>
      {/* ══ P1-09: 今日军报统计卡片 ══ */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))',
        gap: 10,
        marginBottom: 16,
      }}>
        {STAT_CARDS.map((card) => {
          const value = countStates(card.states);
          return (
            <div
              key={card.label}
              onClick={() => handleStatClick(card)}
              style={{
                background: card.bg,
                border: `1px solid ${card.border}`,
                borderRadius: 12,
                padding: '14px 16px',
                cursor: 'pointer',
                transition: 'transform .12s, border-color .15s',
              }}
              onMouseEnter={(e) => {
                (e.currentTarget as HTMLDivElement).style.transform = 'translateY(-2px)';
                (e.currentTarget as HTMLDivElement).style.borderColor = card.color;
              }}
              onMouseLeave={(e) => {
                (e.currentTarget as HTMLDivElement).style.transform = 'translateY(0)';
                (e.currentTarget as HTMLDivElement).style.borderColor = card.border;
              }}
            >
              <div style={{ fontSize: 11, color: '#5a6b92', marginBottom: 6 }}>{card.icon} {card.label}</div>
              <div style={{ fontSize: 28, fontWeight: 800, color: card.color, lineHeight: 1 }}>{value}</div>
            </div>
          );
        })}

        {/* P3-12: 粮草告急 context pressure card */}
        {(() => {
          const pColor = avgPressure > 80 ? '#ff5270' : avgPressure > 50 ? '#f5c842' : '#2ecc8a';
          const pBg = avgPressure > 80 ? '#200a10' : avgPressure > 50 ? '#201a08' : '#0a2018';
          const pBorder = avgPressure > 80 ? '#ff527044' : avgPressure > 50 ? '#f5c84244' : '#2ecc8a44';
          return (
            <div
              style={{
                background: pBg,
                border: `1px solid ${pBorder}`,
                borderRadius: 12,
                padding: '14px 16px',
                transition: 'transform .12s, border-color .15s',
              }}
              onMouseEnter={(e) => {
                (e.currentTarget as HTMLDivElement).style.transform = 'translateY(-2px)';
                (e.currentTarget as HTMLDivElement).style.borderColor = pColor;
              }}
              onMouseLeave={(e) => {
                (e.currentTarget as HTMLDivElement).style.transform = 'translateY(0)';
                (e.currentTarget as HTMLDivElement).style.borderColor = pBorder;
              }}
            >
              <div style={{ fontSize: 11, color: '#5a6b92', marginBottom: 6 }}>🌾 粮草</div>
              <div style={{ fontSize: 28, fontWeight: 800, color: pColor, lineHeight: 1 }}>{avgPressure}%</div>
              <div style={{ marginTop: 8, height: 6, background: '#0e1320', borderRadius: 3, overflow: 'hidden' }}>
                <div style={{
                  height: '100%',
                  width: `${avgPressure}%`,
                  background: pColor,
                  borderRadius: 3,
                  transition: 'width .3s, background .3s',
                  ...(avgPressure > 80 ? { animation: 'pulse 1s infinite' } : {}),
                }} />
              </div>
            </div>
          );
        })()}
      </div>

      {/* ══ P1-08: Agent 在线状态面板（增强） ══ */}
      {asData && asData.ok && (
        <div className="as-panel">
          <div className="as-header">
            <span className="as-title">🔌 Agent 在线状态</span>
            <span className={`as-gw ${gwCls}`}>Gateway: {gw?.status || '未知'}</span>
            <button className="btn-refresh" onClick={() => loadAgentsStatus()} style={{ marginLeft: 8 }}>
              🔄 刷新
            </button>
            {(offline + unconf > 0) && (
              <button className="btn-refresh" onClick={handleWakeAll} style={{ marginLeft: 4, borderColor: 'var(--warn)', color: 'var(--warn)' }}>
                ⚡ 全部唤醒
              </button>
            )}
          </div>

          {/* Agent cards grid */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))',
            gap: 10,
          }}>
            {filtered.map((a) => {
              const isRunning = a.status === 'running';
              const deptLabel = AGENT_DEPT[a.id] || '';
              const myTasks = deptActiveTasks[deptLabel] || [];
              const currentTask = myTasks[0]; // first active task
              const emoji = AGENT_EMOJI[a.id] || '🤖';
              const name = AGENT_NAMES[a.id] || a.label;
              const canWake = a.status !== 'running' && a.status !== 'unconfigured' && gw?.alive;

              return (
                <div
                  key={a.id}
                  style={{
                    background: 'var(--panel2)',
                    border: `1px solid ${isRunning ? '#6a9eff66' : '#1c2236'}`,
                    borderRadius: 12,
                    padding: 14,
                    position: 'relative',
                    transition: 'border-color .15s, background .15s',
                    ...(isRunning ? { animation: 'pulse 2s ease-in-out infinite' } : {}),
                  }}
                >
                  {/* Status dot */}
                  <div style={{
                    position: 'absolute',
                    top: 8,
                    right: 8,
                    width: 8,
                    height: 8,
                    borderRadius: '50%',
                    background: isRunning ? '#2ecc8a' : a.status === 'idle' ? '#4a5568' : '#ff5270',
                    boxShadow: isRunning ? '0 0 6px #2ecc8a88' : undefined,
                    animation: isRunning || a.status === 'offline' ? 'pulse 1.5s infinite' : undefined,
                  }} />

                  <div style={{ textAlign: 'center', marginBottom: 6 }}>
                    <div style={{ fontSize: 26 }}>{emoji}</div>
                    <div style={{ fontSize: 13, fontWeight: 800, marginTop: 4 }}>{name}</div>
                    <div style={{ fontSize: 10, color: 'var(--muted)', marginTop: 2 }}>
                      {isRunning ? '🔵 忙碌' : a.status === 'idle' ? '🟢 空闲' : a.status === 'offline' ? '🔴 离线' : '⚪ 未配置'}
                    </div>
                  </div>

                  {/* Current task info */}
                  {isRunning && currentTask ? (
                    <div style={{
                      marginTop: 8,
                      padding: '6px 8px',
                      background: '#0a1228',
                      borderRadius: 6,
                      borderLeft: '2px solid var(--acc)',
                      cursor: 'pointer',
                    }} onClick={() => setModalTaskId(currentTask.id)}>
                      <div style={{ fontSize: 10, color: 'var(--acc)', fontWeight: 700, marginBottom: 2 }}>
                        {currentTask.id}
                      </div>
                      <div style={{
                        fontSize: 11,
                        color: 'var(--text)',
                        fontWeight: 600,
                        lineHeight: 1.3,
                        display: '-webkit-box',
                        WebkitLineClamp: 2,
                        WebkitBoxOrient: 'vertical',
                        overflow: 'hidden',
                      }}>
                        {currentTask.title || '(无标题)'}
                      </div>
                      {currentTask.now && currentTask.now !== '-' && (
                        <div style={{ fontSize: 10, color: 'var(--muted)', marginTop: 2 }}>
                          📍 {currentTask.now.substring(0, 30)}
                        </div>
                      )}
                    </div>
                  ) : isRunning ? (
                    <div style={{ fontSize: 10, color: 'var(--muted)', textAlign: 'center', marginTop: 6 }}>执行中…</div>
                  ) : (
                    <div style={{ fontSize: 10, color: 'var(--muted)', textAlign: 'center', marginTop: 6 }}>待命中</div>
                  )}

                  {/* Wake button */}
                  {canWake && (
                    <div style={{ textAlign: 'center', marginTop: 6 }}>
                      <button className="as-wake-btn" onClick={(e) => { e.stopPropagation(); handleWake(a.id); }}>
                        ⚡ 唤醒
                      </button>
                    </div>
                  )}

                  {/* P3-12: per-agent context pressure bar */}
                  {(() => {
                    const pressure = contextPressureMap[a.id];
                    if (pressure === undefined) return null;
                    const barColor = pressure > 80 ? '#ff5270' : pressure > 50 ? '#f5c842' : '#2ecc8a';
                    return (
                      <div style={{ marginTop: 6 }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 9, color: 'var(--muted)', marginBottom: 2 }}>
                          <span>🌾 上下文</span>
                          <span style={{ color: barColor }}>{pressure}%</span>
                        </div>
                        <div style={{ height: 4, background: '#0e1320', borderRadius: 2, overflow: 'hidden' }}>
                          <div style={{
                            height: '100%',
                            width: `${pressure}%`,
                            background: barColor,
                            borderRadius: 2,
                            transition: 'width .3s',
                            ...(pressure > 80 ? { animation: 'pulse 1s infinite' } : {}),
                          }} />
                        </div>
                      </div>
                    );
                  })()}
                </div>
              );
            })}
          </div>

          <div className="as-summary">
            <span><span className="as-dot running" style={{ position: 'static', width: 8, height: 8 }} /> {running} 运行中</span>
            <span><span className="as-dot idle" style={{ position: 'static', width: 8, height: 8 }} /> {idle} 待命</span>
            {offline > 0 && <span><span className="as-dot offline" style={{ position: 'static', width: 8, height: 8 }} /> {offline} 离线</span>}
            {unconf > 0 && <span><span className="as-dot unconfigured" style={{ position: 'static', width: 8, height: 8 }} /> {unconf} 未配置</span>}
            <span style={{ marginLeft: 'auto', fontSize: 10, color: 'var(--muted)' }}>
              检测于 {(asData.checkedAt || '').substring(11, 19)}
            </span>
          </div>
        </div>
      )}

      {/* ══ Duty Grid (existing) ══ */}
      <div className="duty-grid">
        {DEPTS.map((d) => {
          const myTasks = activeTasks.filter((t) => t.org === d.label);
          const isActive = myTasks.some((t) => t.state === 'Doing' || t.state === 'executing');
          const isBlocked = myTasks.some((t) => t.state === 'Blocked');
          const off = offMap[d.id];
          const hb = off?.heartbeat || { status: 'idle', label: '⚪' };
          const dotCls = isBlocked ? 'blocked' : isActive ? 'busy' : hb.status === 'active' ? 'active' : 'idle';
          const statusText = isBlocked ? '⚠️ 阻塞' : isActive ? '⚙️ 执行中' : hb.status === 'active' ? '🟢 活跃' : '⚪ 候命';
          const cardCls = isBlocked ? 'blocked-card' : isActive ? 'active-card' : '';

          return (
            <div key={d.id} className={`duty-card ${cardCls}`}>
              <div className="dc-hdr">
                <span className="dc-emoji">{d.emoji}</span>
                <div className="dc-info">
                  <div className="dc-name">{d.label}</div>
                  <div className="dc-role">{d.role} · {d.rank}</div>
                </div>
                <div className="dc-status">
                  <span className={`dc-dot ${dotCls}`} />
                  <span>{statusText}</span>
                </div>
              </div>
              <div className="dc-body">
                {myTasks.length > 0 ? (
                  myTasks.map((t) => (
                    <div key={t.id} className="dc-task" onClick={() => setModalTaskId(t.id)}>
                      <div className="dc-task-id">{t.id}</div>
                      <div className="dc-task-title">{t.title || '(无标题)'}</div>
                      {t.now && t.now !== '-' && (
                        <div className="dc-task-now">{t.now.substring(0, 70)}</div>
                      )}
                      <div className="dc-task-meta">
                        <span className={`tag st-${t.state}`}>{stateLabel(t)}</span>
                        {t.block && t.block !== '无' && (
                          <span className="tag" style={{ borderColor: '#ff527044', color: 'var(--danger)' }}>🚫{t.block}</span>
                        )}
                      </div>
                    </div>
                  ))
                ) : (
                  <div className="dc-idle">
                    <span style={{ fontSize: 20 }}>🪭</span>
                    <span>候命中</span>
                  </div>
                )}
              </div>
              <div className="dc-footer">
                <span className="dc-model">🤖 {off?.model_short || '待配置'}</span>
                {off?.last_active && <span className="dc-la">⏰ {off.last_active}</span>}
              </div>
            </div>
          );
        })}
      </div>

      {/* ══ P3-11: 引擎巡营 / 操作区 ══ */}
      <div style={{
        marginTop: 16,
        padding: 16,
        background: 'var(--panel2)',
        border: '1px solid var(--line)',
        borderRadius: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: scanResult ? 12 : 0 }}>
          <button
            className="btn btn-g"
            onClick={handleSchedulerScan}
            disabled={scanLoading}
            style={{ minWidth: 120 }}
          >
            {scanLoading ? '⏳ 巡营中...' : '🔍 引擎巡营'}
          </button>
          {scanResult && (
            <span style={{ fontSize: 12, color: scanResult.zombies > 0 ? '#ff5270' : '#2ecc8a' }}>
              {scanResult.zombies > 0
                ? `⚠️ 发现 ${scanResult.zombies} 个僵尸任务`
                : '✅ 一切正常'}
            </span>
          )}
        </div>

        {scanResult && scanResult.zombies > 0 && (
          <div style={{
            display: 'flex',
            flexDirection: 'column',
            gap: 6,
          }}>
            {scanResult.actions.map((act, i) => (
              <div key={i} style={{
                fontSize: 11,
                color: 'var(--text)',
                padding: '4px 8px',
                background: '#0e1320',
                borderRadius: 6,
                borderLeft: '2px solid #ff5270',
              }}>
                <span style={{ color: '#ff5270', fontWeight: 700 }}>{act.taskId}</span>
                <span style={{ color: 'var(--muted)', marginLeft: 8 }}>{act.action}</span>
                {act.stalledSec != null && (
                  <span style={{ color: '#f5c842', marginLeft: 8 }}>卡住 {Math.round(act.stalledSec / 60)} 分钟</span>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
