"use client"

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

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

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

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

  if (data.length === 0) return null

  const chartData = data.map((d) => ({
    name: t(`types.${d.practiceType}` as const),
    sessionCount: d.sessionCount,
    totalQuestions: d.totalQuestions,
    correctCount: d.correctCount,
    accuracy: Number((d.accuracy * 100).toFixed(0)),
  }))

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

  return (
    <Card className={cn("overflow-hidden", className)}>
      <CardHeader>
        <CardTitle className="text-base">{t("teacher.typeBreakdown.title")}</CardTitle>
        <CardDescription>{t("teacher.typeBreakdown.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}
            />
            <YAxis tickLine={false} axisLine={false} width={36} />
            <ChartTooltip
              content={
                <ChartTooltipContent
                  className="w-[220px]"
                  formatter={(payload: unknown) => {
                    const p = payload as unknown as {
                      name: string
                      sessionCount: number
                      totalQuestions: number
                      correctCount: number
                      accuracy: number
                    }
                    return (
                      <div className="space-y-1.5">
                        <div className="font-medium">{p.name}</div>
                        <div className="text-muted-foreground">
                          {t("teacher.classComparison.totalSessions")}：
                          <span className="font-medium text-foreground">{p.sessionCount}</span>
                        </div>
                        <div className="text-muted-foreground">
                          {t("teacher.classComparison.totalAnswered")}：
                          <span className="font-medium text-foreground">{p.totalQuestions}</span>
                        </div>
                        <div className="text-muted-foreground">
                          {t("teacher.knowledgePointWeakness.wrongAnswers")}：
                          <span className="font-medium text-rose-600">{p.totalQuestions - p.correctCount}</span>
                        </div>
                        <div className="text-muted-foreground">
                          {t("teacher.classComparison.averageAccuracy")}：
                          <span className="font-medium text-emerald-600">{p.accuracy}%</span>
                        </div>
                      </div>
                    )
                  }}
                />
              }
            />
            <Bar dataKey="sessionCount" radius={[4, 4, 0, 0]}>
              {chartData.map((_, idx) => (
                <Cell key={idx} fill={CHART_COLORS[idx % CHART_COLORS.length]} />
              ))}
            </Bar>
          </BarChart>
        </ChartContainer>
      </CardContent>
    </Card>
  )
}
