import { useState } from 'react';
import { api } from '../api';
import { useStore } from '../store';
import type { CheckpointInfo, HumanInputCheckpoint } from '../api';

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

// ── Decision Checkpoint ──

function DecisionCheckpoint({
  taskId,
  info,
  onDone,
}: {
  taskId: string;
  info: CheckpointInfo;
  onDone: () => void;
}) {
  const cp = info.checkpoint;
  const [selected, setSelected] = useState<string | null>(null);
  const [note, setNote] = useState('');
  const [loading, setLoading] = useState(false);
  const toast = useStore((s) => s.toast);

  const handleSubmit = async () => {
    if (!selected) return;
    setLoading(true);
    try {
      const r = await api.humanInputRespond(taskId, {
        node_id: info.node_id,
        action: 'decide',
        selected_option: selected,
        reason: note,
      });
      if (r.ok) { toast('✅ 已御批', 'ok'); onDone(); }
      else toast(r.error || '操作失败', 'err');
    } catch { toast('服务器连接失败', 'err'); }
    setLoading(false);
  };

  return (
    <div>
      <div style={{ fontSize: 13, color: 'var(--muted)', lineHeight: 1.6, marginBottom: 14, padding: 12, background: 'var(--panel2)', borderRadius: 8 }}>
        {cp.description}
      </div>
      {/* 关联产出物 */}
      {cp.artifacts?.length ? (
        <div style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 4 }}>📦 关联产出物</div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {cp.artifacts.map((a, i) => (
              <a key={i} href={api.artifactDownloadUrl(taskId, a.path)} target="_blank" rel="noreferrer"
                style={{ fontSize: 10, padding: '2px 8px', borderRadius: 4, border: '1px solid var(--line)', color: 'var(--fg)', textDecoration: 'none' }}>
                📄 {a.name} ↗
              </a>
            ))}
          </div>
        </div>
      ) : null}
      {/* 方案 */}
      <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--muted)', marginBottom: 8 }}>📋 备选方案</div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
        {cp.options?.map((opt) => (
          <div key={opt.id}
            onClick={() => setSelected(opt.id)}
            style={{
              flex: '1 1 180px', padding: 14, borderRadius: 10, cursor: 'pointer',
              border: `2px solid ${selected === opt.id ? 'var(--acc)' : 'var(--line)'}`,
              background: selected === opt.id ? 'rgba(201,162,39,0.08)' : 'var(--panel)',
              transition: 'all 0.15s',
            }}>
            {opt.recommended && (
              <div style={{ float: 'right', background: '#22c55e', color: '#fff', fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 3 }}>荐</div>
            )}
            <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 4 }}>{opt.label}</div>
            {opt.description && <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 6 }}>{opt.description}</div>}
            {opt.pros?.map((p, i) => <div key={i} style={{ fontSize: 11, color: '#22c55e' }}>👍 {p}</div>)}
            {opt.cons?.map((c, i) => <div key={i} style={{ fontSize: 11, color: '#ef4444' }}>👎 {c}</div>)}
          </div>
        ))}
      </div>
      {/* 兜底自由输入 */}
      {(!cp.options || cp.options.length === 0) && (
        <div style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 4 }}>无预定义方案，请直接输入决策：</div>
          <textarea style={{ width: '100%', height: 60, background: 'var(--panel2)', border: '1px solid var(--line)', borderRadius: 6, padding: 8, color: 'var(--fg)', fontSize: 12 }}
            value={note} onChange={(e) => setNote(e.target.value)} placeholder="输入你的决策..." />
        </div>
      )}
      {/* 御批备注 */}
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 4 }}>📝 御批备注（可选）</div>
        <textarea style={{ width: '100%', height: 48, background: 'var(--panel2)', border: '1px solid var(--line)', borderRadius: 6, padding: 8, color: 'var(--fg)', fontSize: 12 }}
          value={note} onChange={(e) => setNote(e.target.value)} placeholder="记录决策理由..." />
      </div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <button className="btn-primary" disabled={!selected || loading} onClick={handleSubmit}>
          🎯 依此方案施行
        </button>
      </div>
    </div>
  );
}

// ── Verify Checkpoint ──

function VerifyCheckpoint({
  taskId,
  info,
  onDone,
}: {
  taskId: string;
  info: CheckpointInfo;
  onDone: () => void;
}) {
  const cp = info.checkpoint;
  const [reason, setReason] = useState('');
  const [showReject, setShowReject] = useState(false);
  const [loading, setLoading] = useState(false);
  const toast = useStore((s) => s.toast);

  const handleAction = async (action: string) => {
    if (action === 'reject' && !showReject) { setShowReject(true); return; }
    setLoading(true);
    try {
      const r = await api.humanInputRespond(taskId, {
        node_id: info.node_id,
        action,
        reason,
      });
      if (r.ok) { toast(action === 'approve' ? '✅ 已御批' : '❌ 已驳回', 'ok'); onDone(); }
      else toast(r.error || '操作失败', 'err');
    } catch { toast('服务器连接失败', 'err'); }
    setLoading(false);
  };

  return (
    <div>
      <div style={{ fontSize: 13, color: 'var(--muted)', lineHeight: 1.6, marginBottom: 12, padding: 12, background: 'var(--panel2)', borderRadius: 8 }}>
        {cp.description}
      </div>
      {/* 自动核验 */}
      {cp.autoCheckResults?.length ? (
        <div style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', marginBottom: 6 }}>自动核验结果</div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {cp.autoCheckResults.map((r, i) => (
              <span key={i} style={{ fontSize: 11, padding: '3px 10px', borderRadius: 4, background: r.passed ? '#22c55e22' : '#ef444422', color: r.passed ? '#22c55e' : '#ef4444' }}>
                {r.passed ? '✅' : '❌'} {r.label}
              </span>
            ))}
          </div>
        </div>
      ) : null}
      {/* 人工核验步骤 */}
      {cp.verificationSteps?.length ? (
        <div style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', marginBottom: 6 }}>人工核验步骤</div>
          <div style={{ fontSize: 12, lineHeight: 1.8, paddingLeft: 16, borderLeft: '2px solid var(--line)' }}>
            {cp.verificationSteps.map((s, i) => <div key={i}>{i + 1}. {s}</div>)}
          </div>
        </div>
      ) : null}
      {/* 关联产出物 */}
      {cp.artifacts?.length ? (
        <div style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 4 }}>📦 关联产出物</div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {cp.artifacts.map((a, i) => (
              <a key={i} href={api.artifactDownloadUrl(taskId, a.path)} target="_blank" rel="noreferrer"
                style={{ fontSize: 10, padding: '2px 8px', borderRadius: 4, border: '1px solid var(--line)', color: 'var(--fg)', textDecoration: 'none' }}>
                📄 {a.name} ↗
              </a>
            ))}
          </div>
        </div>
      ) : null}
      {/* 驳回输入 */}
      {showReject && (
        <div style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 4 }}>驳回缘由</div>
          <textarea style={{ width: '100%', height: 60, background: 'var(--panel2)', border: '1px solid var(--line)', borderRadius: 6, padding: 8, color: 'var(--fg)', fontSize: 12 }}
            value={reason} onChange={(e) => setReason(e.target.value)} placeholder="请说明驳回原因..." />
        </div>
      )}
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
        <button className="btn-ghost" style={{ color: '#ef4444', borderColor: '#ef444444' }} onClick={() => handleAction('reject')} disabled={loading}>
          ❌ 驳回另议
        </button>
        <button className="btn-primary" style={{ background: 'linear-gradient(135deg, #22c55e, #16a34a)' }} onClick={() => handleAction('approve')} disabled={loading}>
          ✅ 御批依准施行
        </button>
      </div>
    </div>
  );
}

// ── Action Checkpoint ──

function ActionCheckpoint({
  taskId,
  info,
  onDone,
}: {
  taskId: string;
  info: CheckpointInfo;
  onDone: () => void;
}) {
  const cp = info.checkpoint;
  const steps = cp.actionSteps || [];
  const [completedSteps, setCompletedSteps] = useState<Set<string>>(new Set());
  const [note, setNote] = useState('');
  const [loading, setLoading] = useState(false);
  const toast = useStore((s) => s.toast);

  const toggleStep = (id: string) => {
    setCompletedSteps((prev) => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  };

  const allDone = completedSteps.size >= steps.length;

  const handleSubmit = async () => {
    if (!allDone) return;
    setLoading(true);
    try {
      const r = await api.humanInputRespond(taskId, {
        node_id: info.node_id,
        action: 'complete',
        completed_steps: Array.from(completedSteps),
        verification_note: note,
      });
      if (r.ok) { toast('✅ 已确认', 'ok'); onDone(); }
      else toast(r.error || '操作失败', 'err');
    } catch { toast('服务器连接失败', 'err'); }
    setLoading(false);
  };

  return (
    <div>
      <div style={{ fontSize: 13, color: 'var(--muted)', lineHeight: 1.6, marginBottom: 12, padding: 12, background: 'var(--panel2)', borderRadius: 8 }}>
        {cp.description}
      </div>
      {/* 进度条 */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
        <div style={{ flex: 1, background: 'var(--panel2)', borderRadius: 4, height: 6, overflow: 'hidden' }}>
          <div style={{ height: '100%', borderRadius: 4, background: '#f59e0b', transition: 'width 0.3s', width: `${steps.length ? (completedSteps.size / steps.length * 100) : 0}%` }} />
        </div>
        <span style={{ fontSize: 11, color: 'var(--muted)' }}>{completedSteps.size}/{steps.length} 步骤</span>
      </div>
      {/* 步骤列表 */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 }}>
        {steps.map((s) => (
          <div key={s.id} onClick={() => toggleStep(s.id)} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: 10, background: 'var(--panel2)', borderRadius: 8, cursor: 'pointer' }}>
            <div style={{
              width: 20, height: 20, borderRadius: 4, border: `2px solid ${completedSteps.has(s.id) ? '#22c55e' : 'var(--line)'}`,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, flexShrink: 0,
              background: completedSteps.has(s.id) ? '#22c55e' : 'transparent', color: '#fff',
            }}>{completedSteps.has(s.id) ? '✓' : ''}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, fontWeight: 600, textDecoration: completedSteps.has(s.id) ? 'line-through' : 'none' }}>{s.description}</div>
              {s.command && (
                <pre style={{ marginTop: 4, fontSize: 11, padding: '4px 8px', background: '#0d1117', borderRadius: 4, color: '#e6edf3', fontFamily: 'monospace' }}>{s.command}</pre>
              )}
            </div>
          </div>
        ))}
      </div>
      {/* 验证命令 */}
      {cp.verificationCommand && (
        <div style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 4 }}>验证命令</div>
          <pre style={{ fontSize: 11, padding: '6px 10px', background: '#0d1117', borderRadius: 6, color: '#e6edf3', fontFamily: 'monospace' }}>{cp.verificationCommand}</pre>
        </div>
      )}
      {/* 验证说明 */}
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 4 }}>验证结果说明</div>
        <input style={{ width: '100%', background: 'var(--panel2)', border: '1px solid var(--line)', borderRadius: 6, padding: '6px 10px', color: 'var(--fg)', fontSize: 12 }}
          value={note} onChange={(e) => setNote(e.target.value)} placeholder="如：返回 200 OK，服务正常运行" />
      </div>
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
        <button className="btn-primary" disabled={!allDone || loading} onClick={handleSubmit} title={allDone ? '' : '请完成所有步骤后提交'}>
          ✅ 臣已办妥，继续执行
        </button>
      </div>
    </div>
  );
}

// ── 主面板 ──

export default function CheckpointPanel({
  taskId,
  checkpoints,
  onDone,
}: {
  taskId: string;
  checkpoints: CheckpointInfo[];
  onDone: () => void;
}) {
  const [activeIdx, setActiveIdx] = useState(0);
  const info = checkpoints[activeIdx];
  if (!info) return null;

  const cp = info.checkpoint;
  const typeIcon = cp.type === 'verify' ? '🔍' : cp.type === 'decision' ? '🎯' : '🔧';
  const typeColor = cp.type === 'verify' ? '#6a9eff' : cp.type === 'decision' ? '#818cf8' : '#f59e0b';
  const typeLabel = cp.type === 'verify' ? '验证 Checkpoint' : cp.type === 'decision' ? '决策 Checkpoint' : '执行 Checkpoint';

  return (
    <div>
      {/* 多节点 Tab */}
      {checkpoints.length > 1 && (
        <div style={{ display: 'flex', borderBottom: '1px solid var(--line)', marginBottom: 12 }}>
          {checkpoints.map((c, i) => (
            <button key={c.node_id}
              className={`tab-btn ${i === activeIdx ? 'active' : ''}`}
              onClick={() => setActiveIdx(i)}
              style={{ fontSize: 12, color: i === activeIdx ? typeColor : 'var(--muted)', borderBottomColor: i === activeIdx ? typeColor : 'transparent' }}
            >🛐 {c.node_name}</button>
          ))}
        </div>
      )}

      {/* 类型头部 */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <div style={{ width: 36, height: 36, borderRadius: '50%', background: `${typeColor}22`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16 }}>{typeIcon}</div>
        <div>
          <div style={{ fontSize: 14, fontWeight: 700, color: typeColor }}>{typeLabel}</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>节点 {info.node_name}（{AGENT_EMOJI[info.agent_id] || ''} {info.agent_id}）</div>
        </div>
      </div>

      {/* 标题 */}
      <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 6 }}>{cp.title}</div>

      {/* 按类型渲染 */}
      {cp.type === 'verify' && <VerifyCheckpoint taskId={taskId} info={info} onDone={onDone} />}
      {cp.type === 'decision' && <DecisionCheckpoint taskId={taskId} info={info} onDone={onDone} />}
      {cp.type === 'action' && <ActionCheckpoint taskId={taskId} info={info} onDone={onDone} />}
    </div>
  );
}
