"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 { Badge } from "@/shared/components/ui/badge"
import { cn } from "@/shared/lib/utils"

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

interface KnowledgePointWeaknessChartProps {
  data: KnowledgePointWeakness[]
  className?: string
}

/**
 * 知识点薄弱度图表
 * 横向柱状图，按错题数降序
 * 颜色按掌握率区分（红/黄/绿）
 * 显示所属章节
 */
export function KnowledgePointWeaknessChart({
  data,
  className,
}: KnowledgePointWeaknessChartProps) {
  if (data.length === 0) return null

  const chartData = data.map((d) => ({
    name: d.knowledgePointName,
    errorCount: d.errorCount,
    masteredCount: d.masteredCount,
    masteryRate: Number((d.masteryRate * 100).toFixed(0)),
    chapterTitle: d.chapterTitle ?? "未分类",
  }))

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

  return (
    <Card className={cn("overflow-hidden", className)}>
      <CardHeader>
        <CardTitle className="text-base">薄弱知识点 Top {data.length}</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <ChartContainer config={chartConfig} className="h-[320px] w-full">
          <BarChart
            data={chartData}
            layout="vertical"
            margin={{ left: 8, right: 16, top: 8, bottom: 8 }}
          >
            <CartesianGrid horizontal={false} strokeDasharray="4 4" strokeOpacity={0.4} />
            <XAxis type="number" tickLine={false} axisLine={false} />
            <YAxis
              type="number"
              dataKey="name"
              tickLine={false}
              axisLine={false}
              width={100}
              tickFormatter={(value: string) =>
                value.length > 8 ? `${value.slice(0, 8)}...` : value
              }
            />
            <ChartTooltip
              content={
                <ChartTooltipContent
                  className="w-[240px]"
                  formatter={(payload: unknown) => {
                    const p = payload as unknown as {
                      name: string
                      errorCount: number
                      masteredCount: number
                      masteryRate: number
                      chapterTitle: string
                    }
                    return (
                      <div className="space-y-1.5">
                        <div className="font-medium">{p.name}</div>
                        <div className="text-xs text-muted-foreground">
                          所属章节：{p.chapterTitle}
                        </div>
                        <div className="text-muted-foreground">
                          错题数：<span className="font-medium text-foreground">{p.errorCount}</span>
                          <span className="ml-2">已掌握：<span className="font-medium text-emerald-600">{p.masteredCount}</span></span>
                        </div>
                        <div className="text-muted-foreground">
                          掌握率：<span className="font-medium text-foreground">{p.masteryRate}%</span>
                        </div>
                      </div>
                    )
                  }}
                />
              }
            />
            <Bar dataKey="errorCount" radius={[0, 4, 4, 0]}>
              {chartData.map((entry, idx) => (
                <Cell
                  key={idx}
                  fill={
                    entry.masteryRate < 30
                      ? "var(--color-rose-500)"
                      : entry.masteryRate < 60
                        ? "var(--color-amber-500)"
                        : "var(--color-emerald-500)"
                  }
                />
              ))}
            </Bar>
          </BarChart>
        </ChartContainer>

        {/* 知识点详情列表（带章节归属） */}
        <div className="space-y-2">
          {data.slice(0, 8).map((kp) => (
            <div
              key={kp.knowledgePointId}
              className="flex items-center justify-between gap-3 rounded-lg border p-2.5"
            >
              <div className="min-w-0 flex-1">
                <div className="truncate text-sm font-medium">{kp.knowledgePointName}</div>
                {kp.chapterTitle ? (
                  <div className="truncate text-xs text-muted-foreground">
                    {kp.chapterTitle}
                  </div>
                ) : null}
              </div>
              <div className="flex shrink-0 items-center gap-2">
                <Badge
                  variant={
                    kp.masteryRate < 0.3
                      ? "destructive"
                      : kp.masteryRate < 0.6
                        ? "secondary"
                        : "outline"
                  }
                  className="text-xs"
                >
                  {Math.round(kp.masteryRate * 100)}%
                </Badge>
                <span className="text-sm font-bold text-rose-600">{kp.errorCount}</span>
              </div>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  )
}
