import { BarChart3, TrendingDown, TrendingUp, Minus } from "lucide-react"

import { Badge } from "@/shared/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { formatDate } from "@/shared/lib/utils"
import type { StudentDashboardGradeProps } from "@/modules/homework/types"

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

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

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

type SubjectGroup = {
  subject: string
  items: StudentDashboardGradeProps["trend"]
  average: number
  count: number
}

const groupBySubject = (
  trend: StudentDashboardGradeProps["trend"],
): SubjectGroup[] => {
  const map = new Map<string, StudentDashboardGradeProps["trend"]>()
  for (const item of trend) {
    const subject = item.assignmentTitle.split(" - ")[0]?.trim() || "General"
    const list = map.get(subject) ?? []
    list.push(item)
    map.set(subject, list)
  }
  const groups: SubjectGroup[] = []
  for (const [subject, items] of map.entries()) {
    const sum = items.reduce((s, i) => s + i.percentage, 0)
    groups.push({
      subject,
      items: items.sort((a, b) => a.submittedAt.localeCompare(b.submittedAt)),
      average: items.length > 0 ? sum / items.length : 0,
      count: items.length,
    })
  }
  return groups.sort((a, b) => b.average - a.average)
}

/**
 * 成绩详情视图：按科目分组展示，每个科目显示平均分、趋势、最近成绩。
 * 用于详情页 grades tab，提供单科分析能力。
 */
export function ChildGradeDetail({ grades }: { grades: StudentDashboardGradeProps }) {
  if (grades.trend.length === 0) {
    return (
      <EmptyState
        icon={BarChart3}
        title="No graded work yet"
        description="Finish and submit assignments to see score analysis."
        className="border-none shadow-none h-48"
      />
    )
  }

  const groups = groupBySubject(grades.trend)
  const overallAvg =
    grades.trend.reduce((s, i) => s + i.percentage, 0) / grades.trend.length

  return (
    <div className="space-y-4" aria-label="Grade analysis by subject">
      <Card>
        <CardHeader className="pb-2">
          <CardTitle className="flex items-center justify-between text-base">
            <span className="flex items-center gap-2">
              <BarChart3 className="h-4 w-4 text-muted-foreground" aria-hidden />
              Overall Average
            </span>
            <span className="tabular-nums">{Math.round(overallAvg)}%</span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-xs text-muted-foreground">
            {groups.length} {groups.length === 1 ? "subject" : "subjects"} · {grades.trend.length}{" "}
            graded {grades.trend.length === 1 ? "assignment" : "assignments"}
          </div>
        </CardContent>
      </Card>

      {groups.map((group) => {
        const percentages = group.items.map((i) => i.percentage)
        const trend = computeTrend(percentages)
        const latest = group.items[group.items.length - 1]
        const best = Math.max(...percentages)
        return (
          <Card key={group.subject}>
            <CardHeader className="pb-2">
              <CardTitle className="flex items-center justify-between text-base">
                <span>{group.subject}</span>
                <div className="flex items-center gap-2">
                  <Badge variant="outline" className="tabular-nums">
                    Avg {Math.round(group.average)}%
                  </Badge>
                  <TrendIcon direction={trend} />
                </div>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="grid grid-cols-3 gap-2 text-center text-xs">
                <div className="rounded-md bg-muted/50 p-2">
                  <div className="text-muted-foreground">Latest</div>
                  <div className="font-semibold tabular-nums">
                    {latest ? `${Math.round(latest.percentage)}%` : "-"}
                  </div>
                </div>
                <div className="rounded-md bg-muted/50 p-2">
                  <div className="text-muted-foreground">Best</div>
                  <div className="font-semibold tabular-nums">{Math.round(best)}%</div>
                </div>
                <div className="rounded-md bg-muted/50 p-2">
                  <div className="text-muted-foreground">Count</div>
                  <div className="font-semibold tabular-nums">{group.count}</div>
                </div>
              </div>

              <div className="space-y-1.5">
                <div className="text-xs font-medium uppercase text-muted-foreground">
                  Recent Grades
                </div>
                {group.items.slice(-3).reverse().map((item) => (
                  <div
                    key={item.assignmentId}
                    className="flex min-h-[36px] items-center justify-between rounded-md border bg-card p-2"
                  >
                    <div className="min-w-0 flex-1">
                      <div className="text-sm font-medium truncate">
                        {item.assignmentTitle}
                      </div>
                      <div className="text-xs text-muted-foreground">
                        {formatDate(item.submittedAt)}
                      </div>
                    </div>
                    <Badge variant="secondary" className="tabular-nums shrink-0 ml-2">
                      {item.score}/{item.maxScore}
                    </Badge>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )
      })}
    </div>
  )
}
