import { Table, Tag } from 'antd'
import type { Exam } from '../types'
import { EXAM_TYPE_LABELS } from '../types'

interface Props {
  exams: Exam[]
  subjectNames: Record<number, string>
}

export default function ScoreOverview({ exams, subjectNames }: Props) {
  const subjectIds = new Set<number>()
  exams.forEach((e) => e.scores.forEach((s) => subjectIds.add(s.subject_id)))
  const sortedSubjects = [...subjectIds].sort((a, b) => a - b)

  const columns = [
    { title: '日期', dataIndex: 'exam_date', key: 'date', width: 110, fixed: 'left' as const },
    {
      title: '类型',
      dataIndex: 'exam_type',
      key: 'type',
      width: 80,
      render: (t: keyof typeof EXAM_TYPE_LABELS) => (
        <Tag>{EXAM_TYPE_LABELS[t]}</Tag>
      ),
    },
    ...sortedSubjects.map((sid) => ({
      title: subjectNames[sid] || `科目${sid}`,
      key: `s${sid}`,
      width: 100,
      render: (_: unknown, exam: Exam) => {
        const score = exam.scores.find((s) => s.subject_id === sid)
        if (!score) return '-'
        return `${score.obtained_score}/${score.total_score} (${(score.ratio * 100).toFixed(1)}%)`
      },
    })),
  ]

  const volatileExams = exams.filter((exam) => {
    return exam.scores.some((s) => {
      const allScores = exams
        .filter((e) => e.exam_date <= exam.exam_date)
        .flatMap((e) => e.scores.filter((sc) => sc.subject_id === s.subject_id))
        .sort((a, b) => {
          const ea = exams.find((e) => e.scores.includes(a))
          const eb = exams.find((e) => e.scores.includes(b))
          return (ea?.exam_date || '').localeCompare(eb?.exam_date || '')
        })
      const idx = allScores.findIndex((sc) => sc.id === s.id)
      if (idx <= 0) return false
      return Math.abs(allScores[idx].ratio - allScores[idx - 1].ratio) >= 0.08
    })
  })

  return (
    <div>
      {volatileExams.length > 0 && (
        <div style={{ marginBottom: 16, padding: 12, background: '#fff7e6', borderRadius: 8 }}>
          <strong>波动预警：</strong>
          {volatileExams.slice(0, 5).map((e) => (
            <Tag key={e.id} color="orange" style={{ marginTop: 4 }}>
              {e.exam_date} {EXAM_TYPE_LABELS[e.exam_type]}
            </Tag>
          ))}
        </div>
      )}
      <Table
        rowKey="id"
        columns={columns}
        dataSource={[...exams].sort((a, b) => b.exam_date.localeCompare(a.exam_date))}
        pagination={{ pageSize: 15 }}
        scroll={{ x: 'max-content' }}
        size="small"
      />
    </div>
  )
}
