import { useMemo } from 'react'
import { Empty, Progress, Table, Tag, Tooltip } from 'antd'
import type { CaseState } from '../hooks/useRunSession'
import { colors, statusColors } from '../tokens'
import { RULE_TYPE_DESC, RULE_TYPE_LABEL, formatRuleScore, ruleTypeLabel } from '../utils/ruleLabels'

interface RuleOverviewProps {
  cases: CaseState[]
  onSelectCase?: (caseId: string) => void
}

export default function RuleOverview({ cases, onSelectCase }: RuleOverviewProps) {
  const ruleTypes = useMemo(() => {
    const set = new Set<string>()
    for (const c of cases) for (const r of c.ruleResults) set.add(r.rule_type)
    return Array.from(set)
  }, [cases])

  const stats = useMemo(() => {
    const perRule: Record<string, { pass: number; total: number }> = {}
    let totalRules = 0
    let passedRules = 0
    let passedCases = 0
    for (const c of cases) {
      for (const r of c.ruleResults) {
        const s = (perRule[r.rule_type] ??= { pass: 0, total: 0 })
        s.total += 1
        totalRules += 1
        if (r.passed) { s.pass += 1; passedRules += 1 }
      }
      if (c.ruleResults.length > 0 && c.ruleResults.every((r) => r.passed)) passedCases += 1
    }
    return { perRule, totalRules, passedRules, passedCases, totalCases: cases.length }
  }, [cases])

  if (ruleTypes.length === 0) {
    return (
      <Empty
        image={Empty.PRESENTED_IMAGE_SIMPLE}
        description="待评测规则将在执行完成后展示"
        style={{ marginTop: 60 }}
      />
    )
  }

  const columns: any[] = [
    {
      title: '用例',
      dataIndex: 'caseId',
      key: 'caseId',
      fixed: 'left',
      width: 180,
      render: (id: string) => (
        <a
          onClick={() => onSelectCase?.(id)}
          style={{ fontSize: 12, color: colors.text, fontWeight: 500 }}
        >
          {id}
        </a>
      ),
    },
    ...ruleTypes.map((t) => ({
      title: (
        <div style={{ lineHeight: 1.3 }}>
          <div style={{ fontSize: 12 }}>{RULE_TYPE_LABEL[t] ?? t}</div>
          <div style={{ fontSize: 10, color: colors.textMuted, fontWeight: 400 }}>{RULE_TYPE_DESC[t] ?? ''}</div>
        </div>
      ),
      dataIndex: t,
      key: t,
      width: 140,
      render: (r: any) => {
        if (!r) return <span style={{ color: '#d9d9d9' }}>-</span>
        return (
          <Tooltip title={r.reason || ruleTypeLabel(t)}>
            <Tag color={r.passed ? 'success' : 'error'} style={{ fontSize: 11, margin: 0 }}>
              {r.passed ? '✓' : '✗'} {formatRuleScore(t, r.score)}
            </Tag>
          </Tooltip>
        )
      },
    })),
  ]

  const data = cases
    .filter((c) => c.ruleResults.length > 0)
    .map((c) => ({
      key: c.caseId,
      caseId: c.caseId,
      ...Object.fromEntries(c.ruleResults.map((r) => [r.rule_type, r])),
    }))

  return (
    <div style={{ padding: '4px 4px 0' }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: `repeat(${ruleTypes.length + 2}, minmax(0, 1fr))`,
        gap: 8,
        marginBottom: 14,
      }}>
        <StatCard label="用例总数" value={String(stats.totalCases)} />
        <StatCard
          label="用例通过率"
          value={stats.totalCases ? `${Math.round((stats.passedCases / stats.totalCases) * 100)}%` : '-'}
          subtitle={`${stats.passedCases} / ${stats.totalCases}`}
          color={ratioColor(stats.passedCases, stats.totalCases)}
        />
        {ruleTypes.map((t) => {
          const s = stats.perRule[t]
          const pct = s && s.total ? Math.round((s.pass / s.total) * 100) : 0
          return (
            <StatCard
              key={t}
              label={RULE_TYPE_LABEL[t] ?? t}
              value={`${pct}%`}
              subtitle={s ? `${s.pass} / ${s.total} 通过` : '暂无'}
              color={ratioColor(s?.pass ?? 0, s?.total ?? 0)}
            >
              <Progress
                percent={pct}
                size="small"
                showInfo={false}
                strokeColor={ratioColor(s?.pass ?? 0, s?.total ?? 0)}
                style={{ marginTop: 4 }}
              />
            </StatCard>
          )
        })}
      </div>

      <Table
        size="small"
        pagination={false}
        columns={columns}
        dataSource={data}
        scroll={{ x: true }}
      />
    </div>
  )
}

function ratioColor(pass: number, total: number): string {
  if (!total) return colors.textMuted
  const r = pass / total
  if (r >= 0.8) return statusColors.completed
  if (r >= 0.5) return '#faad14'
  return statusColors.failed
}

function StatCard({ label, value, subtitle, color, children }: {
  label: string
  value: string
  subtitle?: string
  color?: string
  children?: React.ReactNode
}) {
  return (
    <div style={{
      border: `1px solid ${colors.border}`,
      borderRadius: 8,
      padding: '10px 12px',
      background: '#fff',
    }}>
      <div style={{ fontSize: 11, color: colors.textSecondary }}>{label}</div>
      <div style={{ fontSize: 20, fontWeight: 600, color: color ?? colors.text, marginTop: 2 }}>{value}</div>
      {subtitle && <div style={{ fontSize: 11, color: colors.textMuted }}>{subtitle}</div>}
      {children}
    </div>
  )
}
