"use client"

import type { JSX } from "react"
import { useMemo } from "react"
import { BarChart3 } from "lucide-react"
import { useTranslations } from "next-intl"

import { ChartCardShell } from "@/shared/components/charts/chart-card-shell"
import { TrendLineChart } from "@/shared/components/charts/trend-line-chart"
import { formatDate } from "@/shared/lib/utils"
import type { RankingTrendResult } from "../types"

/**
 * 排名趋势图组件。
 *
 * v3-P1-3：学生页面显示排名趋势，Y 轴反转（第 1 名在顶部）。
 * 对比同类 K12 系统（PowerSchool、Infinite Campus 等）的排名趋势功能。
 */
export function RankingTrendCard({ trend }: { trend: RankingTrendResult | null }): JSX.Element {
  const t = useTranslations("grades")

  const chartData = useMemo(() => {
    if (!trend || trend.points.length === 0) return []
    return trend.points.map((p) => ({
      title: p.title,
      rank: p.rank,
      totalStudents: p.totalStudents,
      fullTitle: p.title,
      submittedAt: formatDate(p.date),
    }))
  }, [trend])

  const hasData = chartData.length > 0
  const maxRank = useMemo(() => {
    if (chartData.length === 0) return 1
    return Math.max(...chartData.map((d) => d.rank), 1)
  }, [chartData])

  return (
    <ChartCardShell
      title={t("analytics.rankingTrend")}
      icon={BarChart3}
      iconClassName="text-muted-foreground"
      isEmpty={!hasData}
      emptyTitle={t("trend.empty")}
      emptyDescription={t("trendCard.emptyDescription")}
      emptyClassName="h-64"
    >
      <div
        className="rounded-md border bg-card p-4"
        role="img"
        aria-label={
          hasData
            ? t("rankingTrend.ariaLabelNonEmpty", { count: chartData.length })
            : t("rankingTrend.ariaLabelEmpty")
        }
      >
        <TrendLineChart
          data={chartData}
          series={[
            {
              dataKey: "rank",
              name: t("analytics.ranking"),
              color: "hsl(var(--primary))",
              dotRadius: 4,
              activeDotRadius: 6,
            },
          ]}
          yDomain={[Math.max(maxRank, 1), 1]}
          yTickFormatter={(value: number) => `#${value}`}
          heightClassName="h-60"
          margin={{ left: 12, right: 12, top: 12, bottom: 12 }}
          yWidth={40}
          tooltipClassName="w-52"
        />
      </div>
    </ChartCardShell>
  )
}
