"use client"

import { Bar, BarChart, CartesianGrid, XAxis, YAxis, Cell } from "recharts"
import { useTranslations } from "next-intl"
import { BarChart3 } from "lucide-react"

import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from "@/shared/components/ui/chart"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { cn } from "@/shared/lib/utils"

import type { ClassKnowledgePointWeakness } from "@/modules/adaptive-practice/data-access-analytics"

interface ClassKnowledgePointWeaknessChartProps {
  data: ClassKnowledgePointWeakness[]
  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 ClassKnowledgePointWeaknessChart({
  data,
  className,
}: ClassKnowledgePointWeaknessChartProps) {
  const t = useTranslations("practice")

  if (data.length === 0) {
    return (
      <Card className={cn("shadow-none", className)}>
        <CardHeader>
          <CardTitle className="text-base">{t("teacher.knowledgePointWeakness.title")}</CardTitle>
          <CardDescription>{t("teacher.knowledgePointWeakness.description")}</CardDescription>
        </CardHeader>
        <CardContent>
          <EmptyState
            icon={BarChart3}
            title={t("teacher.knowledgePointWeakness.noData")}
            description={t("teacher.knowledgePointWeakness.noDataDescription")}
            className="h-[280px] bg-card"
          />
        </CardContent>
      </Card>
    )
  }

  const chartData = data.map((d) => ({
    name: d.knowledgePointName,
    errorRate: Number((d.errorRate * 100).toFixed(0)),
    totalAnswers: d.totalAnswers,
    wrongAnswers: d.wrongAnswers,
  }))

  const chartConfig: ChartConfig = {
    errorRate: {
      label: t("teacher.knowledgePointWeakness.errorRate"),
      color: "var(--color-chart-1)",
    },
  }

  return (
    <Card className={cn("overflow-hidden shadow-none", className)}>
      <CardHeader>
        <CardTitle className="text-base">{t("teacher.knowledgePointWeakness.title")}</CardTitle>
        <CardDescription>{t("teacher.knowledgePointWeakness.description")}</CardDescription>
      </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={40}
              tickFormatter={(value: number) => `${value}%`}
            />
            <ChartTooltip
              content={
                <ChartTooltipContent
                  className="w-[220px]"
                  formatter={(payload: unknown) => {
                    const p = payload as unknown as {
                      name: string
                      errorRate: number
                      totalAnswers: number
                      wrongAnswers: number
                    }
                    return (
                      <div className="space-y-1.5">
                        <div className="font-medium">{p.name}</div>
                        <div className="text-muted-foreground">
                          {t("teacher.knowledgePointWeakness.totalAnswers")}：
                          <span className="font-medium text-foreground">{p.totalAnswers}</span>
                        </div>
                        <div className="text-muted-foreground">
                          {t("teacher.knowledgePointWeakness.wrongAnswers")}：
                          <span className="font-medium text-rose-600">{p.wrongAnswers}</span>
                        </div>
                        <div className="text-muted-foreground">
                          {t("teacher.knowledgePointWeakness.errorRate")}：
                          <span className="font-medium text-rose-600">{p.errorRate}%</span>
                        </div>
                      </div>
                    )
                  }}
                />
              }
            />
            <Bar dataKey="errorRate" radius={[4, 4, 0, 0]}>
              {chartData.map((_, idx) => (
                <Cell key={idx} fill={CHART_COLORS[idx % CHART_COLORS.length]} />
              ))}
            </Bar>
          </BarChart>
        </ChartContainer>
      </CardContent>
    </Card>
  )
}
