import { useEffect, useState } from 'react'
import { Empty, Table, Tag, Tooltip } from 'antd'
import type { CaseState } from '../hooks/useRunSession'
import type { CaseSnapshot } from '../api'
import GeneratedMessages from './GeneratedMessages'
import TurnList from './TurnList'
import { colors, statusColors } from '../tokens'
import { formatRuleScore, ruleTypeLabel } from '../utils/ruleLabels'

interface CaseDetailProps {
  cases: CaseState[]
  snapshots: Record<string, CaseSnapshot>
  focusCaseId?: string | null
}

export default function CaseDetail({ cases, snapshots, focusCaseId }: CaseDetailProps) {
  const [selectedId, setSelectedId] = useState<string | null>(null)

  useEffect(() => {
    if (focusCaseId && cases.some((c) => c.caseId === focusCaseId)) {
      setSelectedId(focusCaseId)
      return
    }
    if (!selectedId || !cases.some((c) => c.caseId === selectedId)) {
      // Prefer first failed case, else first
      const failed = cases.find((c) => c.ruleResults.some((r) => !r.passed))
      setSelectedId((failed ?? cases[0])?.caseId ?? null)
    }
  }, [focusCaseId, cases])

  const selected = cases.find((c) => c.caseId === selectedId) ?? null

  if (cases.length === 0) {
    return (
      <Empty
        image={Empty.PRESENTED_IMAGE_SIMPLE}
        description="暂无用例记录"
        style={{ marginTop: 60 }}
      />
    )
  }

  return (
    <div style={{ display: 'flex', gap: 12, height: '100%', minHeight: 0 }}>
      <div style={{
        flexShrink: 0,
        width: 200,
        border: `1px solid ${colors.border}`,
        borderRadius: 8,
        overflowY: 'auto',
        background: '#fff',
      }}>
        {cases.map((c) => {
          const allPassed = c.ruleResults.length > 0 && c.ruleResults.every((r) => r.passed)
          const hasFailed = c.ruleResults.some((r) => !r.passed)
          const dot = hasFailed ? statusColors.failed
                    : allPassed ? statusColors.completed
                    : c.status === 'running' ? statusColors.running
                    : colors.textMuted
          const isSel = c.caseId === selectedId
          return (
            <div
              key={c.caseId}
              onClick={() => setSelectedId(c.caseId)}
              style={{
                padding: '8px 10px',
                borderBottom: `1px solid ${colors.border}`,
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                gap: 8,
                background: isSel ? '#e6f4ff55' : undefined,
                borderLeft: isSel ? `3px solid ${colors.primary}` : `3px solid transparent`,
                fontSize: 12,
              }}
            >
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: dot, flexShrink: 0 }} />
              <span style={{
                flex: 1,
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                fontWeight: isSel ? 600 : 400,
              }}>
                {c.caseId}
              </span>
            </div>
          )
        })}
      </div>

      <div style={{ flex: 1, minWidth: 0, overflowY: 'auto', padding: '0 4px' }}>
        {selected ? (
          <CaseDetailBody cs={selected} snapshot={snapshots[selected.caseId]} />
        ) : (
          <Empty description="请选择一个用例" style={{ marginTop: 60 }} />
        )}
      </div>
    </div>
  )
}

function CaseDetailBody({ cs, snapshot }: { cs: CaseState; snapshot?: CaseSnapshot }) {
  return (
    <div>
      {snapshot && <MetaBlock snapshot={snapshot} />}

      {cs.generatedMessages && cs.generatedMessages.length > 0 && (
        <GeneratedMessages messages={cs.generatedMessages} />
      )}

      <div style={{ marginBottom: 12 }}>
        <TurnList turns={cs.turns} errors={cs.errors} />
      </div>

      {cs.ruleResults.length > 0 && (
        <div style={{
          border: `1px solid ${colors.border}`,
          borderRadius: 8,
          padding: 12,
          background: '#fff',
        }}>
          <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 8 }}>规则评分</div>
          <Table
            size="small"
            pagination={false}
            columns={[
              {
                title: '规则', dataIndex: 'rule_type', key: 'rule_type', width: 140,
                render: (t: string) => ruleTypeLabel(t),
              },
              {
                title: '结果', dataIndex: 'passed', key: 'passed', width: 80,
                render: (p: boolean) => (
                  <Tag color={p ? 'success' : 'error'} style={{ fontSize: 11 }}>{p ? '通过' : '未通过'}</Tag>
                ),
              },
              {
                title: '分数', key: 'score', width: 100,
                render: (_: any, r: any) => formatRuleScore(r.rule_type, r.score),
              },
              {
                title: '原因', dataIndex: 'reason', key: 'reason',
                render: (v: string) => (
                  <Tooltip title={v}>
                    <span style={{
                      display: 'inline-block',
                      maxWidth: 340,
                      whiteSpace: 'nowrap',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      fontSize: 12,
                    }}>{v || '-'}</span>
                  </Tooltip>
                ),
              },
            ]}
            dataSource={cs.ruleResults.map((r, i) => ({ key: i, ...r }))}
          />
        </div>
      )}
    </div>
  )
}

function MetaBlock({ snapshot }: { snapshot: CaseSnapshot }) {
  const e = snapshot.expectations
  const items: { label: string; value: string }[] = [
    { label: '类型', value: typeLabel(snapshot.type) },
  ]
  if (e.intent) items.push({ label: '目标意图', value: e.intent })
  if (e.keywords_include?.length) items.push({ label: '需包含', value: e.keywords_include.join('、') })
  if (e.keywords_exclude?.length) items.push({ label: '需排除', value: e.keywords_exclude.join('、') })
  if (e.response_time_max_ms) items.push({ label: '响应上限', value: `${e.response_time_max_ms} ms` })
  if (e.coherence_min_score != null) items.push({ label: '连贯性最低分', value: String(e.coherence_min_score) })
  if (snapshot.type === 'dynamic') {
    if (snapshot.turns) items.push({ label: '生成轮数', value: String(snapshot.turns) })
    if (snapshot.prompt) items.push({ label: '生成提示', value: snapshot.prompt })
  }

  return (
    <div style={{
      border: `1px solid ${colors.border}`,
      borderRadius: 8,
      padding: 12,
      background: colors.bgSubtle,
      marginBottom: 12,
    }}>
      <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 6 }}>{snapshot.id} · 用例配置</div>
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))',
        gap: 6,
        fontSize: 12,
        color: colors.textSecondary,
      }}>
        {items.map((it, i) => (
          <div key={i}>
            <b style={{ color: colors.text }}>{it.label}：</b>{it.value}
          </div>
        ))}
      </div>
    </div>
  )
}

function typeLabel(t: string): string {
  if (t === 'dynamic') return 'AI 动态'
  if (t === 'multi_turn') return '多轮'
  if (t === 'single') return '单轮'
  return t
}
