import ReactECharts from 'echarts-for-react'
import { useMemo } from 'react'
import type { Exam, ReviewStatus } from '../types'
import { REVIEW_STATUS_LABELS } from '../types'

interface Props {
  exams: Exam[]
  selectedSubject?: string | null
  onSubjectSelect?: (subject: string) => void
}

const STATUS_ORDER: ReviewStatus[] = ['careless', 'unknown', 'nervous', 'normal']

const STATUS_COLORS: Record<ReviewStatus, string> = {
  careless: '#fa8c16',
  unknown: '#ff4d4f',
  nervous: '#722ed1',
  normal: '#52c41a',
}

function buildChartData(exams: Exam[]) {
  const subjectSet = new Set<string>()
  const counts: Record<ReviewStatus, Record<string, number>> = {
    careless: {},
    unknown: {},
    nervous: {},
    normal: {},
  }

  for (const exam of exams) {
    for (const score of exam.scores) {
      const subjectName = score.subject_name || `科目${score.subject_id}`
      subjectSet.add(subjectName)
      for (const status of score.review_statuses || []) {
        counts[status][subjectName] = (counts[status][subjectName] || 0) + 1
      }
    }
  }

  const subjects = Array.from(subjectSet).sort((a, b) => a.localeCompare(b, 'zh-CN'))
  return { subjects, counts }
}

export default function ReviewBarChart({ exams, selectedSubject, onSubjectSelect }: Props) {
  const hasData = STATUS_ORDER.some((status) =>
    exams.some((exam) =>
      exam.scores.some((score) => (score.review_statuses || []).includes(status)),
    ),
  )

  const { subjects, counts } = useMemo(() => buildChartData(exams), [exams])

  if (!hasData) {
    return (
      <div style={{ textAlign: 'center', padding: 32, color: '#999' }}>
        暂无复盘数据，请在下方填写各科考试状态
      </div>
    )
  }

  const option = {
    title: {
      text: '各科考试状态统计',
      subtext: selectedSubject ? `当前选中：${selectedSubject}` : '点击柱子查看明细',
      left: 'center',
      textStyle: { fontSize: 15, fontWeight: 500 },
      subtextStyle: { fontSize: 12, color: '#888' },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params: Array<{ seriesName: string; value: number; marker: string; name: string }>) => {
        const rows = params.filter((p) => p.value > 0)
        if (!rows.length) return ''
        const total = rows.reduce((sum, p) => sum + p.value, 0)
        return (
          `<strong>${params[0]?.name || ''}</strong><br/>` +
          rows.map((p) => `${p.marker}${p.seriesName}: ${p.value} 次`).join('<br/>') +
          `<br/>合计: ${total} 次`
        )
      },
    },
    legend: {
      bottom: 0,
      data: STATUS_ORDER.map((s) => REVIEW_STATUS_LABELS[s]),
    },
    grid: { left: 48, right: 24, top: 64, bottom: 56 },
    xAxis: {
      type: 'category',
      data: subjects,
      axisLabel: {
        interval: 0,
        rotate: subjects.length > 6 ? 30 : 0,
        color: (value: string) => (value === selectedSubject ? '#1677ff' : '#666'),
        fontWeight: (value: string) => (value === selectedSubject ? ('bold' as const) : ('normal' as const)),
      },
    },
    yAxis: {
      type: 'value',
      name: '次数',
      minInterval: 1,
      splitLine: { lineStyle: { type: 'dashed' } },
    },
    series: STATUS_ORDER.map((status) => ({
      name: REVIEW_STATUS_LABELS[status],
      type: 'bar',
      stack: 'review',
      barMaxWidth: 48,
      emphasis: { focus: 'series' },
      data: subjects.map((subject) => {
        const value = counts[status][subject] || 0
        const selected = subject === selectedSubject
        return {
          value,
          itemStyle: {
            color: STATUS_COLORS[status],
            borderRadius: status === 'normal' ? [2, 2, 0, 0] : 0,
            opacity: selectedSubject && !selected ? 0.45 : 1,
            borderColor: selected ? '#1677ff' : 'transparent',
            borderWidth: selected ? 2 : 0,
          },
        }
      }),
    })),
  }

  const onEvents = {
    click: (params: { componentType?: string; name?: string }) => {
      if (params.componentType === 'series' && params.name) {
        onSubjectSelect?.(params.name)
      }
    },
  }

  return (
    <div>
      <ReactECharts
        option={option}
        style={{ height: 360, width: '100%' }}
        notMerge
        onEvents={onEvents}
      />
      <p style={{ color: '#888', fontSize: 12, marginTop: 8 }}>
        柱状图按科目展示各状态次数（分色堆叠）；点击科目查看每次考试详情，存在问题标红
      </p>
    </div>
  )
}
