import { Tag, Typography } from 'antd'
import { useMemo } from 'react'
import type { Exam } from '../types'
import {
  EXAM_TYPE_LABELS,
  REVIEW_STATUS_LABELS,
  hasReviewProblem,
} from '../types'
import type { ReviewStatus } from '../types'

interface Props {
  exams: Exam[]
  subjectName: string | null
}

interface DetailRow {
  key: string
  examDate: string
  examType: string
  title: string | null
  scoreText: string
  ratioText: string
  statuses: ReviewStatus[]
  isProblem: boolean
}

const STATUS_TAG_COLOR: Record<ReviewStatus, string> = {
  careless: 'orange',
  unknown: 'red',
  nervous: 'purple',
  normal: 'green',
}

export default function ReviewSubjectDetail({ exams, subjectName }: Props) {
  const rows = useMemo(() => {
    if (!subjectName) return []
    const result: DetailRow[] = []
    for (const exam of exams) {
      const score = exam.scores.find(
        (s) => (s.subject_name || `科目${s.subject_id}`) === subjectName,
      )
      if (!score || !score.review_statuses?.length) continue
      result.push({
        key: exam.id,
        examDate: exam.exam_date,
        examType: EXAM_TYPE_LABELS[exam.exam_type],
        title: exam.title,
        scoreText: `${score.obtained_score}/${score.total_score}`,
        ratioText: `${(score.ratio * 100).toFixed(1)}%`,
        statuses: score.review_statuses,
        isProblem: hasReviewProblem(score.review_statuses),
      })
    }
    return result.sort((a, b) => b.examDate.localeCompare(a.examDate))
  }, [exams, subjectName])

  if (!subjectName) {
    return (
      <Typography.Text type="secondary" style={{ display: 'block', padding: '12px 0' }}>
        点击上方柱状图中的科目，查看各次考试详情
      </Typography.Text>
    )
  }

  if (rows.length === 0) {
    return (
      <Typography.Text type="secondary" style={{ display: 'block', padding: '12px 0' }}>
        {subjectName} 暂无复盘记录
      </Typography.Text>
    )
  }

  const problemCount = rows.filter((r) => r.isProblem).length

  return (
    <div style={{ marginTop: 16 }}>
      <Typography.Text strong style={{ fontSize: 15 }}>
        {subjectName} · 考试明细
      </Typography.Text>
      <Typography.Text type="secondary" style={{ marginLeft: 12, fontSize: 12 }}>
        共 {rows.length} 次，其中 {problemCount} 次存在问题
      </Typography.Text>
      <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
        {rows.map((row) => (
          <div
            key={row.key}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 10,
              flexWrap: 'nowrap',
              overflowX: 'auto',
              whiteSpace: 'nowrap',
              padding: '10px 14px',
              borderRadius: 8,
              border: `1px solid ${row.isProblem ? '#ffccc7' : '#f0f0f0'}`,
              background: row.isProblem ? '#fff2f0' : '#fafafa',
            }}
          >
            <Typography.Text strong style={{ color: row.isProblem ? '#cf1322' : undefined }}>
              {row.examDate}
            </Typography.Text>
            <Typography.Text style={{ color: row.isProblem ? '#cf1322' : '#666' }}>
              {row.examType}
            </Typography.Text>
            {row.title && (
              <Typography.Text style={{ color: row.isProblem ? '#cf1322' : '#888' }}>
                {row.title}
              </Typography.Text>
            )}
            <Typography.Text style={{ color: row.isProblem ? '#cf1322' : undefined }}>
              得分 {row.scoreText}（{row.ratioText}）
            </Typography.Text>
            <Typography.Text
              type={row.isProblem ? 'danger' : 'secondary'}
              style={{ fontSize: 13 }}
            >
              状态
            </Typography.Text>
            {row.statuses.map((status) => (
              <Tag
                key={status}
                color={STATUS_TAG_COLOR[status]}
                style={{
                  marginInlineEnd: 0,
                  ...(row.isProblem && status !== 'normal' ? { fontWeight: 600 } : {}),
                }}
              >
                {REVIEW_STATUS_LABELS[status]}
              </Tag>
            ))}
          </div>
        ))}
      </div>
    </div>
  )
}
