"use client"

import { useMemo } from "react"
import { useTranslations } from "next-intl"
import {
  CartesianGrid,
  Scatter,
  ScatterChart,
  XAxis,
  YAxis,
  ZAxis,
  Cell,
} from "recharts"
import { TrendingDown, AlertTriangle, CheckCircle2, Inbox } from "lucide-react"

import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from "@/shared/components/ui/chart"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { cn } from "@/shared/lib/utils"

import type {
  AttendanceGradeCorrelationSummary,
  AttendanceGradeRiskLevel,
} from "../types"

/** 风险等级对应的颜色（散点图着色，与 attendance-sheet 调色板对齐）。 */
const RISK_COLORS: Record<AttendanceGradeRiskLevel, string> = {
  high: "#ef4444", // red-500
  medium: "#f59e0b", // amber-500
  low: "#10b981", // emerald-500
}

/** 风险等级对应的 Badge variant。 */
const RISK_BADGE_VARIANTS: Record<
  AttendanceGradeRiskLevel,
  "destructive" | "default" | "secondary"
> = {
  high: "destructive",
  medium: "default",
  low: "secondary",
}

/** 风险等级图标。 */
const RISK_ICONS: Record<AttendanceGradeRiskLevel, typeof AlertTriangle> = {
  high: TrendingDown,
  medium: AlertTriangle,
  low: CheckCircle2,
}

/** 风险等级图标颜色（Tailwind 类名，与 attendance-sheet 调色板对齐）。 */
const RISK_ICON_CLASSNAMES: Record<AttendanceGradeRiskLevel, string> = {
  high: "text-red-500",
  medium: "text-amber-500",
  low: "text-emerald-500",
}

const chartConfig: ChartConfig = {
  students: {
    label: "Students",
  },
}

/**
 * L-9 考勤与成绩关联分析卡片。
 *
 * 包含：
 * - 顶部汇总：Pearson 相关系数 + 解释 + 风险学生数
 * - 散点图：x=出勤率，y=平均成绩，按风险等级着色
 * - 风险学生表格：列出所有学生的关联数据，按风险降序
 */
export function AttendanceGradeCorrelationCard({
  summary,
}: {
  summary: AttendanceGradeCorrelationSummary | null
}) {
  const t = useTranslations("attendance")

  const scatterData = useMemo(() => {
    if (!summary) return []
    return summary.items.map((it) => ({
      studentId: it.studentId,
      studentName: it.studentName,
      attendanceRate: it.attendanceRate,
      averageScore: it.averageScore,
      riskLevel: it.riskLevel,
      attendanceRecordCount: it.attendanceRecordCount,
      gradeRecordCount: it.gradeRecordCount,
      absentCount: it.absentCount,
    }))
  }, [summary])

  if (!summary) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>{t("correlation.title")}</CardTitle>
        </CardHeader>
        <CardContent>
          <EmptyState
            icon={Inbox}
            title={t("correlation.noData")}
            description={t("correlation.noDataDescription")}
            className="h-auto border-none shadow-none"
          />
        </CardContent>
      </Card>
    )
  }

  const interpretationLabel = t(
    `correlation.interpretation.${summary.correlationInterpretation}`
  )

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t("correlation.title")}</CardTitle>
        <p className="text-sm text-muted-foreground">
          {t("correlation.description", {
            className: summary.className,
            start: summary.startDate,
            end: summary.endDate,
          })}
        </p>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* 顶部汇总指标 */}
        <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
          <SummaryStat
            label={t("correlation.correlationCoefficient")}
            value={
              summary.correlation !== null
                ? summary.correlation.toFixed(4)
                : t("correlation.notAvailable")
            }
            sublabel={interpretationLabel}
          />
          <SummaryStat
            label={t("correlation.riskCounts.high")}
            value={String(summary.riskCounts.high)}
            icon={TrendingDown}
            iconClassName={RISK_ICON_CLASSNAMES.high}
          />
          <SummaryStat
            label={t("correlation.riskCounts.medium")}
            value={String(summary.riskCounts.medium)}
            icon={AlertTriangle}
            iconClassName={RISK_ICON_CLASSNAMES.medium}
          />
          <SummaryStat
            label={t("correlation.riskCounts.low")}
            value={String(summary.riskCounts.low)}
            icon={CheckCircle2}
            iconClassName={RISK_ICON_CLASSNAMES.low}
          />
        </div>

        {/* 散点图 */}
        {scatterData.length > 0 ? (
          <div>
            <h4 className="mb-3 text-sm font-medium">
              {t("correlation.scatterTitle")}
            </h4>
            <ChartContainer
              config={chartConfig}
              className="h-[320px] w-full"
            >
              <ScatterChart
                margin={{ top: 16, right: 16, bottom: 32, left: 16 }}
              >
                <CartesianGrid
                  strokeDasharray="4 4"
                  strokeOpacity={0.4}
                />
                <XAxis
                  type="number"
                  dataKey="attendanceRate"
                  name={t("correlation.attendanceRate")}
                  domain={[0, 100]}
                  tickLine={false}
                  axisLine={false}
                  tickMargin={8}
                  label={{
                    value: t("correlation.attendanceRate"),
                    position: "bottom",
                    offset: 16,
                    style: { fontSize: 12, fill: "hsl(var(--muted-foreground))" },
                  }}
                />
                <YAxis
                  type="number"
                  dataKey="averageScore"
                  name={t("correlation.averageScore")}
                  domain={[0, 100]}
                  tickLine={false}
                  axisLine={false}
                  width={40}
                />
                <ZAxis type="number" range={[60, 60]} />
                <ChartTooltip
                  cursor={{ strokeDasharray: "3 3" }}
                  content={
                    <ChartTooltipContent
                      indicator="dot"
                      hideLabel
                      formatter={(
                        _value: unknown,
                        _name: unknown,
                        item: { payload?: unknown }
                      ) => {
                        const data = item?.payload as
                          | (typeof scatterData)[number]
                          | undefined
                        if (!data) return null
                        return (
                          <div className="space-y-1">
                            <div className="font-medium">{data.studentName}</div>
                            <div className="text-xs text-muted-foreground">
                              {t("correlation.attendanceRate")}:{" "}
                              {data.attendanceRate}%
                            </div>
                            <div className="text-xs text-muted-foreground">
                              {t("correlation.averageScore")}:{" "}
                              {data.averageScore}
                            </div>
                            <div className="text-xs text-muted-foreground">
                              {t("correlation.absentCount")}:{" "}
                              {data.absentCount}
                            </div>
                          </div>
                        )
                      }}
                    />
                  }
                />
                <Scatter
                  name={t("correlation.scatterSeries")}
                  data={scatterData}
                  shape="circle"
                >
                  {scatterData.map((entry) => (
                    <Cell
                      key={entry.studentId}
                      fill={RISK_COLORS[entry.riskLevel]}
                      fillOpacity={0.7}
                    />
                  ))}
                </Scatter>
              </ScatterChart>
            </ChartContainer>
            {/* 风险等级图例 */}
            <div className="mt-3 flex flex-wrap items-center gap-4 text-xs">
              {(["high", "medium", "low"] as const).map((level) => (
                <div key={level} className="flex items-center gap-1.5">
                  <span
                    className="inline-block h-3 w-3 rounded-full"
                    style={{ backgroundColor: RISK_COLORS[level] }}
                    aria-hidden="true"
                  />
                  <span className="text-muted-foreground">
                    {t(`correlation.riskLevel.${level}`)}
                  </span>
                </div>
              ))}
            </div>
          </div>
        ) : (
          <EmptyState
            icon={Inbox}
            title={t("correlation.noStudents")}
            description={t("correlation.noStudentsDescription")}
            className="h-auto border-none shadow-none"
          />
        )}

        {/* 学生明细表格 */}
        {summary.items.length > 0 && (
          <div>
            <h4 className="mb-3 text-sm font-medium">
              {t("correlation.studentDetails")}
            </h4>
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t("list.columns.student")}</TableHead>
                    <TableHead className="text-right">
                      {t("correlation.attendanceRate")}
                    </TableHead>
                    <TableHead className="text-right">
                      {t("correlation.absentCount")}
                    </TableHead>
                    <TableHead className="text-right">
                      {t("correlation.averageScore")}
                    </TableHead>
                    <TableHead className="text-right">
                      {t("correlation.gradeRecordCount")}
                    </TableHead>
                    <TableHead>{t("correlation.riskLevelLabel")}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {summary.items.map((item) => {
                    const Icon = RISK_ICONS[item.riskLevel]
                    return (
                      <TableRow key={item.studentId}>
                        <TableCell className="font-medium">
                          {item.studentName}
                        </TableCell>
                        <TableCell className="text-right tabular-nums">
                          {item.attendanceRate}%
                        </TableCell>
                        <TableCell className="text-right tabular-nums text-muted-foreground">
                          {item.absentCount}
                        </TableCell>
                        <TableCell className="text-right tabular-nums">
                          {item.averageScore}
                        </TableCell>
                        <TableCell className="text-right tabular-nums text-muted-foreground">
                          {item.gradeRecordCount}
                        </TableCell>
                        <TableCell>
                          <Badge variant={RISK_BADGE_VARIANTS[item.riskLevel]}>
                            <Icon className="mr-1 h-3 w-3" aria-hidden="true" />
                            {t(`correlation.riskLevel.${item.riskLevel}`)}
                          </Badge>
                        </TableCell>
                      </TableRow>
                    )
                  })}
                </TableBody>
              </Table>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  )
}

/** 汇总统计项（label + value + 可选图标/副标题）。 */
function SummaryStat({
  label,
  value,
  sublabel,
  icon: Icon,
  iconClassName,
}: {
  label: string
  value: string
  sublabel?: string
  icon?: typeof AlertTriangle
  iconClassName?: string
}) {
  return (
    <div className="rounded-lg border bg-muted/30 p-4">
      <div className="flex items-center justify-between">
        <p className="text-xs text-muted-foreground">{label}</p>
        {Icon && (
          <Icon
            className={cn("h-4 w-4", iconClassName)}
            aria-hidden="true"
          />
        )}
      </div>
      <p className="mt-2 text-2xl font-semibold tabular-nums">{value}</p>
      {sublabel && (
        <p className="mt-1 text-xs text-muted-foreground">{sublabel}</p>
      )}
    </div>
  )
}
