import { useState } from 'react'
import {
  Alert, Button, Card, Col, Descriptions, Empty, Input, Modal, Popconfirm, Progress, Row, Space, Spin, Tag, message,
} from 'antd'
import { FileTextOutlined, HistoryOutlined, NodeIndexOutlined, StopOutlined } from '@ant-design/icons'
import { intelligentEvalsApi, type IntelligentEval } from '../../api'
import { colors } from '../../tokens'
import { formatDateTime, shortDateTime } from '../../utils/date'
import { EVAL_STATUS, SESSION_STATUS } from './status'
import ConfigSnapshots from './ConfigSnapshots'
import DecisionProcess from './DecisionProcess'

const sectionCard: React.CSSProperties = { marginBottom: 16 }

function personaLabel(persona: Record<string, unknown>): string {
  if (typeof persona.name === 'string' && persona.name) return persona.name
  if (typeof persona.background === 'string' && persona.background) return persona.background
  return JSON.stringify(persona)
}

function PlanView({ ev }: { ev: IntelligentEval }) {
  const plan = ev.plan
  if (!plan) return <Empty description="暂无粗计划" image={Empty.PRESENTED_IMAGE_SIMPLE} />
  return (
    <div>
      <Descriptions column={3} size="small" bordered style={{ marginBottom: 12 }}>
        <Descriptions.Item label="预估会话数">{plan.estimated_sessions}</Descriptions.Item>
        <Descriptions.Item label="单会话最大轮数">{plan.budget?.max_turns_per_session ?? '—'}</Descriptions.Item>
        <Descriptions.Item label="总轮数上限">{plan.budget?.total_max_turns ?? '—'}</Descriptions.Item>
      </Descriptions>

      <div style={{ fontWeight: 500, marginBottom: 6 }}>评测维度</div>
      <Space size={6} wrap style={{ marginBottom: 12 }}>
        {(plan.dimensions ?? []).map((d) => <Tag key={d} color="blue">{d}</Tag>)}
      </Space>

      <div style={{ fontWeight: 500, marginBottom: 6 }}>虚拟用户</div>
      <Space direction="vertical" size={4} style={{ width: '100%', marginBottom: 12 }}>
        {(plan.virtual_users ?? []).map((u, i) => (
          <div key={i} style={{ fontSize: 13, color: colors.textSecondary }}>
            <b style={{ color: colors.text }}>{personaLabel(u.persona)}</b> · 目标：{u.goal}
          </div>
        ))}
      </Space>

      <div style={{ fontWeight: 500, marginBottom: 6 }}>时间分布</div>
      <Space direction="vertical" size={4} style={{ width: '100%', marginBottom: 12 }}>
        {(plan.time_distribution ?? []).map((t, i) => (
          <div key={i} style={{ fontSize: 13, color: colors.textSecondary }}>
            <Tag style={{ margin: 0 }}>{t.time_slot}</Tag> {t.sessions} 个会话 · {t.scenario}
          </div>
        ))}
      </Space>

      {plan.completion_criteria && (
        <div style={{ fontSize: 13, color: colors.textSecondary }}>
          <b style={{ color: colors.text }}>完成标准：</b>{plan.completion_criteria}
        </div>
      )}
    </div>
  )
}

interface EvalDetailProps {
  ev: IntelligentEval
  targetName: string
  onOpenReport: () => void
  onChanged: () => void
}

export default function EvalDetail({ ev, targetName, onOpenReport, onChanged }: EvalDetailProps) {
  const [busy, setBusy] = useState(false)
  const [rejectOpen, setRejectOpen] = useState(false)
  const [feedback, setFeedback] = useState('')
  const [showConfigHistory, setShowConfigHistory] = useState(false)
  const [showDecisionProcess, setShowDecisionProcess] = useState(false)
  const meta = EVAL_STATUS[ev.status] ?? { label: ev.status, color: 'default' }
  const showSessions = ev.status === 'executing' || ev.status === 'completed'
  const sessions = showSessions ? ev.sessions ?? [] : []

  const runAction = async (fn: () => Promise<unknown>, okMsg: string) => {
    setBusy(true)
    try {
      await fn()
      message.success(okMsg)
      onChanged()
    } finally {
      setBusy(false)
    }
  }

  const approve = () => runAction(() => intelligentEvalsApi.approve(ev.id), '已批准，进入执行')
  const cancel = () => runAction(() => intelligentEvalsApi.cancel(ev.id), '已取消')
  const submitReject = () => runAction(async () => {
    await intelligentEvalsApi.reject(ev.id, feedback)
    setRejectOpen(false)
    setFeedback('')
  }, '已打回，等待重新规划')

  if (showConfigHistory) {
    return <ConfigSnapshots evalId={ev.id} onBack={() => setShowConfigHistory(false)} />
  }

  if (showDecisionProcess) {
    return <DecisionProcess evalId={ev.id} onBack={() => setShowDecisionProcess(false)} />
  }

  return (
    <div style={{ height: '100%', overflowY: 'auto', padding: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <span style={{ fontSize: 16, fontWeight: 600, color: colors.text }}>{ev.name}</span>
        <Tag color={meta.color}>{meta.label}</Tag>
        <div style={{ flex: 1 }} />
        <Space>
          <Button icon={<HistoryOutlined />} onClick={() => setShowConfigHistory(true)}>配置历史</Button>
          <Button icon={<NodeIndexOutlined />} onClick={() => setShowDecisionProcess(true)}>决策过程</Button>
          {ev.status === 'completed' && (
            <Button type="primary" icon={<FileTextOutlined />} onClick={onOpenReport}>查看报告</Button>
          )}
          {(ev.status === 'pending_approval' || ev.status === 'executing') && (
            <Popconfirm title="取消该智能评估？" onConfirm={cancel}>
              <Button danger icon={<StopOutlined />} loading={busy}>取消</Button>
            </Popconfirm>
          )}
        </Space>
      </div>

      <Row gutter={16}>
        <Col span={9}>
          <Card size="small" title="基本信息" style={sectionCard}>
            <Descriptions column={1} size="small">
              <Descriptions.Item label="评测对象">{targetName}</Descriptions.Item>
              <Descriptions.Item label="时间窗口">{ev.time_window_hours} 小时</Descriptions.Item>
              <Descriptions.Item label="创建时间">{formatDateTime(ev.created_at)}</Descriptions.Item>
              <Descriptions.Item label="开始时间">{formatDateTime(ev.started_at)}</Descriptions.Item>
              <Descriptions.Item label="完成时间">{formatDateTime(ev.completed_at)}</Descriptions.Item>
              <Descriptions.Item label="会话进度">{ev.completed_sessions}/{ev.session_count}</Descriptions.Item>
            </Descriptions>
          </Card>

          <Card size="small" title="用户输入" style={sectionCard}>
            <Descriptions column={1} size="small">
              <Descriptions.Item label="评估目标">{ev.goal || '—'}</Descriptions.Item>
              <Descriptions.Item label="考察意图">{ev.intent || '—'}</Descriptions.Item>
              <Descriptions.Item label="角色描述">
                <span style={{ whiteSpace: 'pre-wrap' }}>{ev.role_description || '—'}</span>
              </Descriptions.Item>
              <Descriptions.Item label="种子集">
                {Object.keys(ev.seeds ?? {}).length === 0
                  ? '—'
                  : (
                    <pre style={{
                      margin: 0, fontSize: 12, background: colors.bgSubtle,
                      padding: 8, borderRadius: 6, overflowX: 'auto',
                    }}
                    >
                      {JSON.stringify(ev.seeds, null, 2)}
                    </pre>
                  )}
              </Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>

        <Col span={15}>
          {ev.status === 'planning' && (
            ev.plan_feedback ? (
              <Alert
                style={sectionCard}
                type="warning"
                showIcon
                message="计划已打回，OpenClaw 正在根据反馈重新规划"
                description={ev.plan_feedback}
              />
            ) : (
              <Card size="small" style={sectionCard}>
                <Spin size="small" />
                <span style={{ marginLeft: 10, color: colors.textSecondary }}>
                  OpenClaw 正在规划，产出粗计划后会自动进入待审批…
                </span>
              </Card>
            )
          )}

          {(ev.status === 'pending_approval' || ev.status === 'executing' || ev.status === 'completed') && (
            <Card
              size="small"
              title="粗计划"
              style={sectionCard}
              extra={ev.status === 'pending_approval' && (
                <Space>
                  <Button size="small" danger onClick={() => setRejectOpen(true)}>打回</Button>
                  <Button size="small" type="primary" loading={busy} onClick={approve}>批准并执行</Button>
                </Space>
              )}
            >
              <PlanView ev={ev} />
            </Card>
          )}

          {showSessions && (
            <Card
              size="small"
              title={`会话进度（${ev.completed_sessions}/${ev.session_count}）`}
              style={sectionCard}
              extra={(
                <Progress
                  percent={ev.session_count ? Math.round((ev.completed_sessions / ev.session_count) * 100) : 0}
                  size="small"
                  style={{ width: 140 }}
                />
              )}
            >
              {sessions.length === 0 && (
                <div style={{ fontSize: 13, color: colors.textSecondary }}>
                  等待 OpenClaw 按粗计划的时间分布创建会话…
                </div>
              )}
              {sessions.map((s) => {
                const sMeta = SESSION_STATUS[s.status]
                return (
                  <div
                    key={s.id}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap',
                      padding: '6px 0', borderBottom: `1px solid ${colors.border}`, fontSize: 13,
                    }}
                  >
                    <b style={{ color: colors.text }}>{personaLabel(s.persona)}</b>
                    <Tag color={sMeta.color} style={{ margin: 0 }}>{sMeta.label}</Tag>
                    {s.dimension && <Tag style={{ margin: 0 }}>{s.dimension}</Tag>}
                    <span style={{ color: colors.textSecondary, flex: 1, minWidth: 120 }}>{s.goal}</span>
                    <span style={{ color: colors.textMuted }}>{s.turn_count} 轮</span>
                    {s.created_at && (
                      <span style={{ color: colors.textMuted }}>{shortDateTime(s.created_at)}</span>
                    )}
                  </div>
                )
              })}
              {ev.status === 'executing' && (
                <div style={{ fontSize: 12, color: colors.textMuted, marginTop: 8 }}>
                  会话由 OpenClaw 按粗计划的时间分布自唤醒创建，本页每 5 秒自动刷新
                </div>
              )}
            </Card>
          )}
        </Col>
      </Row>

      <Modal
        title="打回计划"
        open={rejectOpen}
        onCancel={() => setRejectOpen(false)}
        onOk={submitReject}
        okText="打回"
        okButtonProps={{ danger: true, disabled: !feedback.trim(), loading: busy }}
      >
        <Input.TextArea
          rows={4}
          value={feedback}
          onChange={(e) => setFeedback(e.target.value)}
          placeholder="请填写打回原因与改进方向，OpenClaw 会据此重新规划"
        />
      </Modal>
    </div>
  )
}
