"use client"

import { Bar, BarChart, CartesianGrid, XAxis, YAxis, Cell } from "recharts"
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from "@/shared/components/ui/chart"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { cn } from "@/shared/lib/utils"

import type { ClassErrorOverview } from "@/modules/error-book/types"

interface ClassErrorBarChartProps {
  data: ClassErrorOverview[]
  className?: string
}

const CHART_COLORS = [
  "var(--color-chart-1)",
  "var(--color-chart-2)",
  "var(--color-chart-3)",
  "var(--color-chart-4)",
  "var(--color-chart-5)",
]

/**
 * 班级错题数对比柱状图（教师视图）
 * 横轴：班级名称，纵轴：错题总数
 * 颜色按班级区分，tooltip 显示学生数/人均/掌握率
 */
export function ClassErrorBarChart({ data, className }: ClassErrorBarChartProps) {
  if (data.length === 0) return null

  const chartData = data.map((d) => ({
    name: d.className,
    totalErrorItems: d.totalErrorItems,
    studentCount: d.studentCount,
    averageErrorPerStudent: Number(d.averageErrorPerStudent.toFixed(1)),
    averageMasteryRate: Number((d.averageMasteryRate * 100).toFixed(0)),
    dueReviewCount: d.dueReviewCount,
  }))

  const chartConfig: ChartConfig = {
    totalErrorItems: {
      label: "错题总数",
      color: "var(--color-chart-1)",
    },
  }

  return (
    <Card className={cn("overflow-hidden", className)}>
      <CardHeader>
        <CardTitle className="text-base">各班级错题数对比</CardTitle>
      </CardHeader>
      <CardContent>
        <ChartContainer config={chartConfig} className="h-[280px] w-full">
          <BarChart data={chartData} margin={{ left: 8, right: 8, top: 8, bottom: 8 }}>
            <CartesianGrid vertical={false} strokeDasharray="4 4" strokeOpacity={0.4} />
            <XAxis
              dataKey="name"
              tickLine={false}
              axisLine={false}
              tickMargin={8}
              tickFormatter={(value: string) =>
                value.length > 8 ? `${value.slice(0, 8)}...` : value
              }
            />
            <YAxis tickLine={false} axisLine={false} width={36} />
            <ChartTooltip
              content={
                <ChartTooltipContent
                  className="w-[220px]"
                  formatter={(payload: unknown) => {
                    const p = payload as unknown as {
                      name: string
                      totalErrorItems: number
                      studentCount: number
                      averageErrorPerStudent: number
                      averageMasteryRate: number
                      dueReviewCount: number
                    }
                    return (
                      <div className="space-y-1.5">
                        <div className="font-medium">{p.name}</div>
                        <div className="text-muted-foreground">
                          错题总数：<span className="font-medium text-foreground">{p.totalErrorItems}</span>
                        </div>
                        <div className="text-muted-foreground">
                          学生数：<span className="font-medium text-foreground">{p.studentCount}</span>
                        </div>
                        <div className="text-muted-foreground">
                          人均错题：<span className="font-medium text-foreground">{p.averageErrorPerStudent}</span>
                        </div>
                        <div className="text-muted-foreground">
                          平均掌握率：<span className="font-medium text-foreground">{p.averageMasteryRate}%</span>
                        </div>
                        <div className="text-muted-foreground">
                          待复习：<span className="font-medium text-rose-600">{p.dueReviewCount}</span>
                        </div>
                      </div>
                    )
                  }}
                />
              }
            />
            <Bar dataKey="totalErrorItems" radius={[4, 4, 0, 0]}>
              {chartData.map((_, idx) => (
                <Cell key={idx} fill={CHART_COLORS[idx % CHART_COLORS.length]} />
              ))}
            </Bar>
          </BarChart>
        </ChartContainer>
      </CardContent>
    </Card>
  )
}
