"use client"

import { useTranslations } from "next-intl"
import { Target } from "lucide-react"

import { ChartCardShell } from "@/shared/components/charts/chart-card-shell"
import { ComparisonRadarChart } from "@/shared/components/charts/comparison-radar-chart"
import type { MasteryRadarPoint } from "@/modules/diagnostic/types"

interface MasteryRadarChartProps {
  data: MasteryRadarPoint[]
}

export function MasteryRadarChart({ data }: MasteryRadarChartProps) {
  const t = useTranslations("diagnostic")
  const isEmpty = !data || data.length === 0

  // v2-P2-5: 保留完整 knowledgePoint 作为 angleKey，使 Tooltip 显示完整名称；
  // 通过 angleTickFormatter 截断轴上显示文本，避免长名称溢出图表区域。
  const MAX_AXIS_LABEL_LENGTH = 8
  const truncateAxisLabel = (value: string): string =>
    value.length > MAX_AXIS_LABEL_LENGTH
      ? `${value.slice(0, MAX_AXIS_LABEL_LENGTH)}...`
      : value

  const chartData = isEmpty
    ? []
    : data.map((d) => ({ ...d }))

  const hasClassAverage = !isEmpty && data.some((d) => d.classAverage !== undefined)

  const ariaLabel = isEmpty
    ? t("chart.radarAriaLabelEmpty")
    : t("chart.radarAriaLabelNonEmpty", {
        count: data.length,
        withClassAverage: hasClassAverage ? t("chart.withClassAverage") : "",
      })

  return (
    <ChartCardShell
      title={t("chart.radarTitle")}
      description={t("chart.radarDescriptionNonEmpty")}
      icon={Target}
      isEmpty={isEmpty}
      emptyTitle={t("chart.radarEmptyTitle")}
      emptyDescription={t("chart.noMasteryDataForStudent")}
      emptyClassName="h-60"
    >
      <div
        role="img"
        aria-label={ariaLabel}
        tabIndex={0}
        className="rounded-md focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ring"
      >
        <ComparisonRadarChart
          data={chartData}
          angleKey="knowledgePoint"
          angleTickFormatter={truncateAxisLabel}
          angleTickFontSize={11}
          domain={[0, 100]}
          tickCount={5}
          showLegend={hasClassAverage}
          heightClassName="mx-auto h-96 w-full max-w-lg"
          gridStrokeDasharray="4 4"
          series={[
            {
              dataKey: "student",
              name: t("chart.studentSeries"),
              color: "hsl(var(--primary))",
              fillOpacity: 0.35,
              strokeWidth: 2,
              show: true,
            },
            {
              dataKey: "classAverage",
              name: t("chart.classAvgSeries"),
              color: "hsl(var(--chart-2))",
              fillOpacity: 0.15,
              strokeWidth: 2,
              strokeDasharray: "4 4",
              show: hasClassAverage,
            },
          ]}
        />
      </div>
    </ChartCardShell>
  )
}
