"use client"

import type { JSX } 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 { GradeTrendResult } from "@/modules/grades/types"

interface GradeTrendChartProps {
  data: GradeTrendResult | null
}

export function GradeTrendChart({ data }: GradeTrendChartProps): JSX.Element {
  const t = useTranslations("grades")
  const isEmpty = !data || data.points.length === 0

  const chartData = isEmpty
    ? []
    : data.points.map((p) => ({
        title: p.title,
        normalizedScore: p.normalizedScore,
        fullTitle: p.title,
        date: formatDate(p.date),
        rawScore: p.score,
        fullScore: p.fullScore,
        type: p.type,
      }))

  return (
    <ChartCardShell
      title={t("analytics.trend")}
      description={
        isEmpty
          ? t("trendChart.descriptionEmpty")
          : t("trendChart.descriptionNonEmpty", { label: data.label, average: data.averageScore.toFixed(1) })
      }
      icon={BarChart3}
      isEmpty={isEmpty}
      emptyTitle={t("trendChart.emptyTitle")}
      emptyDescription={t("trendChart.emptyDescription")}
      emptyClassName="h-60"
    >
      <div role="img" aria-label={isEmpty ? t("trendChart.ariaLabelEmpty") : t("trendChart.ariaLabelNonEmpty", { label: data.label, average: data.averageScore.toFixed(1) })}>
        <TrendLineChart
          data={chartData}
          series={[
            {
              dataKey: "normalizedScore",
              name: t("chart.scorePercent"),
              color: "hsl(var(--primary))",
              dotRadius: 3,
              activeDotRadius: 5,
            },
          ]}
          margin={{ left: 8, right: 8, top: 8, bottom: 8 }}
          yWidth={36}
        />
      </div>
    </ChartCardShell>
  )
}
