"use client"

import { useMemo } from "react"
import { useTranslations } from "next-intl"
import { useRouter, usePathname, useSearchParams } from "next/navigation"
import { GitCompare } from "lucide-react"

import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Button } from "@/shared/components/ui/button"
import { Badge } from "@/shared/components/ui/badge"
import { EmptyState } from "@/shared/components/ui/empty-state"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import { SimpleBarChart, type BarSeries } from "@/shared/components/charts/simple-bar-chart"
import { cn } from "@/shared/lib/utils"

import type { ClassComparisonSummary } from "../types"

interface ClassComparisonCardProps {
  summary: ClassComparisonSummary | null
  /** 可选年级列表（用于切换年级）。 */
  grades?: Array<{ id: string; name: string }>
  /** 当前选中的年级 ID。 */
  currentGradeId?: string
}

export function ClassComparisonCard({
  summary,
  grades,
  currentGradeId,
}: ClassComparisonCardProps) {
  const t = useTranslations("attendance.comparison")
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()

  const chartData = useMemo(() => {
    if (!summary) return []
    return summary.items.map((i) => ({
      name: i.className,
      presentRate: i.presentRate,
      lateRate: i.lateRate,
      absentRate: i.absentRate,
    }))
  }, [summary])

  const bars: BarSeries[] = [
    { dataKey: "presentRate", name: t("series.presentRate"), color: "hsl(var(--chart-1))" },
  ]

  const handleGradeChange = (gradeId: string) => {
    const params = new URLSearchParams(searchParams.toString())
    params.set("gradeId", gradeId)
    router.push(`${pathname}?${params.toString()}`)
  }

  // 标记班级是否高于/低于年级平均
  const getRateBadge = (rate: number, average: number) => {
    if (rate > average + 1) {
      return <Badge variant="outline" className="bg-green-500/10 text-green-700 border-green-500/30">{t("aboveAverage")}</Badge>
    }
    if (rate < average - 1) {
      return <Badge variant="outline" className="bg-red-500/10 text-red-700 border-red-500/30">{t("belowAverage")}</Badge>
    }
    return <Badge variant="outline" className="bg-muted text-muted-foreground">{t("average")}</Badge>
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center justify-between gap-2">
          <span className="flex items-center gap-2">
            <GitCompare className="h-5 w-5" />
            {t("title")}
          </span>
          {grades && grades.length > 0 && (
            <div className="flex items-center gap-1">
              {grades.map((g) => (
                <Button
                  key={g.id}
                  type="button"
                  variant={currentGradeId === g.id ? "default" : "outline"}
                  size="sm"
                  className={cn("h-7 px-2 text-xs")}
                  onClick={() => handleGradeChange(g.id)}
                >
                  {g.name}
                </Button>
              ))}
            </div>
          )}
        </CardTitle>
        {summary && (
          <p className="text-sm text-muted-foreground">
            {t("description", {
              grade: summary.gradeName,
              avg: summary.averagePresentRate,
              start: summary.startDate,
              end: summary.endDate,
            })}
          </p>
        )}
      </CardHeader>
      <CardContent className="space-y-4">
        {!summary || summary.items.length === 0 ? (
          <EmptyState
            title={t("noData")}
            description={t("noDataDescription")}
            icon={GitCompare}
            className="border-none shadow-none"
          />
        ) : (
          <>
            <SimpleBarChart
              data={chartData}
              bars={bars}
              xKey="name"
              yDomain={[0, 100]}
              yTickFormatter={(v) => `${v}%`}
              heightClassName="h-[280px]"
            />
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-12">#</TableHead>
                    <TableHead>{t("columns.class")}</TableHead>
                    <TableHead className="text-right">{t("columns.total")}</TableHead>
                    <TableHead className="text-right">{t("columns.presentRate")}</TableHead>
                    <TableHead className="text-right">{t("columns.lateRate")}</TableHead>
                    <TableHead className="text-right">{t("columns.absentRate")}</TableHead>
                    <TableHead className="text-center">{t("columns.badge")}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {summary.items.map((item, idx) => (
                    <TableRow key={item.classId}>
                      <TableCell className="font-medium tabular-nums">{idx + 1}</TableCell>
                      <TableCell>{item.className}</TableCell>
                      <TableCell className="text-right tabular-nums">{item.total}</TableCell>
                      <TableCell className="text-right tabular-nums">{item.presentRate.toFixed(1)}%</TableCell>
                      <TableCell className="text-right tabular-nums">{item.lateRate.toFixed(1)}%</TableCell>
                      <TableCell className="text-right tabular-nums">{item.absentRate.toFixed(1)}%</TableCell>
                      <TableCell className="text-center">
                        {getRateBadge(item.presentRate, summary.averagePresentRate)}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  )
}
