"use client"

import { useMemo } from "react"
import Link from "next/link"
import { BarChart3, TrendingDown, TrendingUp, Minus, Trophy } from "lucide-react"

import { ChartCardShell } from "@/shared/components/charts/chart-card-shell"
import { TrendLineChart } from "@/shared/components/charts/trend-line-chart"
import { Badge } from "@/shared/components/ui/badge"
import { formatDate } from "@/shared/lib/utils"
import type { StudentDashboardGradeProps } from "@/modules/homework/types"

type TrendDirection = "up" | "down" | "flat" | "unknown"

const computeTrend = (trend: { percentage: number }[]): TrendDirection => {
  if (trend.length < 2) return "unknown"
  const latest = trend[trend.length - 1].percentage
  const prev = trend[trend.length - 2].percentage
  if (latest > prev) return "up"
  if (latest < prev) return "down"
  return "flat"
}

const TrendIcon = ({ direction }: { direction: TrendDirection }) => {
  if (direction === "up") {
    return <TrendingUp className="h-4 w-4 text-emerald-600" aria-label="improving" />
  }
  if (direction === "down") {
    return <TrendingDown className="h-4 w-4 text-destructive" aria-label="declining" />
  }
  if (direction === "flat") {
    return <Minus className="h-4 w-4 text-muted-foreground" aria-label="stable" />
  }
  return null
}

export function ChildGradeSummary({
  grades,
  childId,
  childName,
}: {
  grades: StudentDashboardGradeProps
  childId: string
  childName: string
}) {
  const hasGradeTrend = grades.trend.length > 0
  const ranking = grades.ranking
  const latestGrade = grades.trend[grades.trend.length - 1]
  const trendDirection = computeTrend(grades.trend)

  const chartData = useMemo(
    () =>
      grades.trend.map((item, idx) => ({
        title: item.assignmentTitle,
        score: Math.round(item.percentage),
        fullTitle: item.assignmentTitle,
        date: formatDate(item.submittedAt),
        index: idx + 1,
        rawScore: item.score,
        maxScore: item.maxScore,
      })),
    [grades.trend],
  )

  return (
    <ChartCardShell
      title={`${childName}'s Grades`}
      icon={BarChart3}
      iconClassName="text-muted-foreground"
      titleClassName="text-base"
      isEmpty={!hasGradeTrend}
      emptyTitle="No graded work yet"
      emptyDescription="Finish and submit assignments to see score trend."
      emptyClassName="h-48"
    >
      <div
        className="space-y-4"
        aria-label={`Grade trend chart for ${childName}, ${grades.trend.length} records`}
      >
        <div className="grid grid-cols-2 gap-3">
          <div className="rounded-md bg-muted/50 p-3">
            <div className="text-xs text-muted-foreground flex items-center gap-1">
              <BarChart3 className="h-3 w-3" aria-hidden />
              Latest Score
            </div>
            <div className="flex items-center gap-2">
              <div className="text-xl font-semibold tabular-nums">
                {latestGrade ? `${Math.round(latestGrade.percentage)}%` : "-"}
              </div>
              {hasGradeTrend ? <TrendIcon direction={trendDirection} /> : null}
            </div>
            {latestGrade ? (
              <div className="text-xs text-muted-foreground tabular-nums">
                {latestGrade.score}/{latestGrade.maxScore}
              </div>
            ) : null}
          </div>
          <div className="rounded-md bg-muted/50 p-3">
            <div className="text-xs text-muted-foreground flex items-center gap-1">
              <Trophy className="h-3 w-3" aria-hidden />
              Class Rank
            </div>
            <div className="text-xl font-semibold tabular-nums">
              {ranking ? `${ranking.rank}/${ranking.classSize}` : "-"}
            </div>
            {ranking ? (
              <div className="text-xs text-muted-foreground">
                Top {Math.ceil((ranking.rank / ranking.classSize) * 100)}%
              </div>
            ) : null}
          </div>
        </div>

        <div className="rounded-md bg-muted/50 p-3">
          <TrendLineChart
            data={chartData}
            series={[
              {
                dataKey: "score",
                name: "Score (%)",
                color: "hsl(var(--primary))",
                dotRadius: 3,
                activeDotRadius: 5,
              },
            ]}
            xKey="index"
            xTickFormatter={null}
            heightClassName="h-[160px]"
            margin={{ left: 8, right: 8, top: 8, bottom: 8 }}
            yWidth={30}
            tooltipClassName="w-[200px]"
          />
        </div>

        {grades.recent.length > 0 ? (
          <div className="space-y-2">
            <div className="text-xs font-medium uppercase text-muted-foreground">Recent Grades</div>
            {grades.recent.slice(0, 3).map((r) => (
              <Link
                key={r.assignmentId}
                href={`/parent/children/${childId}?tab=grades`}
                className="flex min-h-[44px] items-center justify-between rounded-md border bg-card p-2 hover:bg-muted/50 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
              >
                <div className="min-w-0 flex-1">
                  <div className="font-medium text-sm truncate">{r.assignmentTitle}</div>
                  <div className="text-xs text-muted-foreground">{formatDate(r.submittedAt)}</div>
                </div>
                <Badge variant="secondary" className="tabular-nums shrink-0 ml-2">
                  {r.score}/{r.maxScore}
                </Badge>
              </Link>
            ))}
          </div>
        ) : null}
      </div>
    </ChartCardShell>
  )
}
