"use client"

import { PieChart as PieChartIcon } from "lucide-react"

import { ChartCardShell } from "@/shared/components/charts/chart-card-shell"
import { SimpleBarChart } from "@/shared/components/charts/simple-bar-chart"
import type { GradeDistributionResult } from "@/modules/grades/types"

const BUCKET_COLORS: Record<string, string> = {
  "90-100": "hsl(142, 71%, 45%)",
  "80-89": "hsl(217, 91%, 60%)",
  "70-79": "hsl(43, 96%, 56%)",
  "60-69": "hsl(25, 95%, 53%)",
  "<60": "hsl(0, 84%, 60%)",
}

interface GradeDistributionChartProps {
  data: GradeDistributionResult | null
}

interface DistributionTooltipItem {
  label: string
  count: number
  percentage: number
}

interface DistributionTooltipPayload {
  payload?: DistributionTooltipItem
}

function isDistributionTooltipPayload(v: unknown): v is DistributionTooltipPayload {
  if (typeof v !== "object" || v === null) return false
  const obj = v as Record<string, unknown>
  const inner = obj.payload
  if (inner === undefined || inner === null) return true
  if (typeof inner !== "object") return false
  const item = inner as Record<string, unknown>
  return (
    typeof item.label === "string" &&
    typeof item.count === "number" &&
    typeof item.percentage === "number"
  )
}

export function GradeDistributionChart({ data }: GradeDistributionChartProps) {
  const isEmpty = !data || data.totalCount === 0

  const chartData = isEmpty
    ? []
    : data.buckets.map((b) => ({
        label: b.label,
        count: b.count,
        percentage:
          data.totalCount > 0
            ? Math.round((b.count / data.totalCount) * 1000) / 10
            : 0,
      }))

  return (
    <ChartCardShell
      title="Score Distribution"
      description={
        isEmpty
          ? "Number of students in each score range (normalized to 0-100)."
          : `${data.totalCount} grade record${data.totalCount === 1 ? "" : "s"} across score ranges.`
      }
      icon={PieChartIcon}
      isEmpty={isEmpty}
      emptyTitle="No distribution data"
      emptyDescription="Select a class and subject to view score distribution."
      emptyClassName="h-60"
    >
      <div role="img" aria-label={`分数分布柱状图：${isEmpty ? "暂无数据" : `共 ${data.totalCount} 条成绩记录分布在 5 个分数区间`}`}>
        <SimpleBarChart
          data={chartData}
          bars={[
            {
              dataKey: "count",
              name: "Students",
              color: "hsl(var(--primary))",
            },
          ]}
          xKey="label"
          xTickFormatter={null}
          yAllowDecimals={false}
          yWidth={32}
          heightClassName="h-[280px]"
          margin={{ left: 8, right: 8, top: 8, bottom: 8 }}
          tooltipClassName="w-[200px]"
          cellColors={BUCKET_COLORS}
          tooltipFormatter={(payload: unknown) => {
            if (!isDistributionTooltipPayload(payload)) return null
            const item = payload.payload
            if (!item) return null
            return (
              <div className="flex w-full flex-col gap-0.5">
                <span className="text-sm font-medium">
                  {item.label}: {item.count} student{item.count === 1 ? "" : "s"}
                </span>
                <span className="text-xs text-muted-foreground">{item.percentage}% of total</span>
              </div>
            )
          }}
        />
      </div>
    </ChartCardShell>
  )
}
