"use client"

import { useMemo } from "react"
import { BarChart3 } from "lucide-react"

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 { StudentGradeSummary } from "../types"

export function GradeTrendCard({ summary }: { summary: StudentGradeSummary }) {
  const chartData = useMemo(() => {
    return [...summary.records]
      .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())
      .map((r) => ({
        title: r.title,
        score: Math.round((r.score / r.fullScore) * 100),
        fullTitle: r.title,
        submittedAt: formatDate(r.createdAt),
        rawScore: r.score,
        maxScore: r.fullScore,
      }))
  }, [summary.records])

  const hasData = chartData.length > 0

  return (
    <ChartCardShell
      title="Grade Trend"
      icon={BarChart3}
      iconClassName="text-muted-foreground"
      isEmpty={!hasData}
      emptyTitle="No grade records yet"
      emptyDescription="Your grade trend will appear here once records are added."
      emptyClassName="h-64"
    >
      <div className="rounded-md border bg-card p-4">
        <TrendLineChart
          data={chartData}
          series={[
            {
              dataKey: "score",
              name: "Score (%)",
              color: "hsl(var(--primary))",
              dotRadius: 4,
              activeDotRadius: 6,
            },
          ]}
          heightClassName="h-[240px]"
          margin={{ left: 12, right: 12, top: 12, bottom: 12 }}
          yWidth={30}
          tooltipClassName="w-[200px]"
        />
      </div>
    </ChartCardShell>
  )
}
