"use client"

import type { JSX } from "react"
import { useMemo } from "react"
import Link from "next/link"
import { Brain, ArrowRight } from "lucide-react"
import { useTranslations } from "next-intl"

import { ChartCardShell } from "@/shared/components/charts/chart-card-shell"
import { SimpleBarChart } from "@/shared/components/charts/simple-bar-chart"
import { Button } from "@/shared/components/ui/button"
import type { KnowledgePointStat } from "@/modules/diagnostic/types"

interface KnowledgePointMasteryChartProps {
  /** 知识点掌握度统计数据；为空数组时渲染空状态 */
  data: KnowledgePointStat[]
  /** 链接到的诊断详情页路径（如 "/teacher/diagnostic"） */
  detailHref?: string
}

/** P3-3: 知识点掌握度颜色映射（与 diagnostic 模块 masteryColor 对齐）。 */
function masteryBarColor(level: number): string {
  if (level >= 80) return "hsl(142, 71%, 45%)" // green
  if (level >= 60) return "hsl(43, 96%, 56%)"  // yellow
  if (level >= 40) return "hsl(25, 95%, 53%)"  // orange
  return "hsl(0, 84%, 60%)" // red
}

interface MasteryTooltipItem {
  label: string
  averageMastery: number
  masteredCount: number
  notMasteredCount: number
  totalStudents: number
}

interface MasteryTooltipPayload {
  payload?: MasteryTooltipItem
}

function isMasteryTooltipPayload(v: unknown): v is MasteryTooltipPayload {
  if (typeof v !== "object" || v === null) return false
  const obj = v as Record<string, unknown>
  const inner = obj.payload
  if (inner === undefined || inner === null) return true
  if (typeof inner !== "object") return false
  const item = inner as Record<string, unknown>
  return (
    typeof item.label === "string" &&
    typeof item.averageMastery === "number" &&
    typeof item.masteredCount === "number" &&
    typeof item.notMasteredCount === "number" &&
    typeof item.totalStudents === "number"
  )
}

/**
 * P3-3: 知识点掌握度图表（集成 diagnostic 模块到 grades analytics 页面）。
 *
 * 展示内容：
 * 1. 按掌握度升序排列的知识点柱状图（薄弱点优先突出）
 * 2. 颜色编码：≥80 绿色（优秀）、60-79 黄色（良好）、40-59 橙色（待提升）、<40 红色（薄弱）
 * 3. 前 3 个薄弱知识点摘要
 * 4. 跳转到完整诊断页的链接
 *
 * 数据来源：调用 diagnostic.data-access.getClassMasterySummary 获取 KnowledgePointStat[]
 */
export function KnowledgePointMasteryChart({
  data,
  detailHref,
}: KnowledgePointMasteryChartProps): JSX.Element {
  const t = useTranslations("grades")

  const { chartData, sortedStats, weakPoints, averageMastery, cellColors } = useMemo(() => {
    if (data.length === 0) {
      return {
        chartData: [],
        sortedStats: [],
        weakPoints: [],
        averageMastery: 0,
        cellColors: {} as Record<string, string>,
      }
    }

    // 按掌握度升序排列（薄弱点优先）
    const sorted = [...data].sort((a, b) => a.averageMastery - b.averageMastery)
    const avg = Math.round(
      (sorted.reduce((sum, s) => sum + s.averageMastery, 0) / sorted.length) * 100
    ) / 100

    // 柱状图数据
    const points = sorted.map((s) => ({
      label: s.knowledgePointName,
      averageMastery: s.averageMastery,
      masteredCount: s.masteredCount,
      notMasteredCount: s.notMasteredCount,
      totalStudents: s.totalStudents,
    }))

    // 单元格颜色映射
    const colors: Record<string, string> = {}
    for (const s of sorted) {
      colors[s.knowledgePointName] = masteryBarColor(s.averageMastery)
    }

    // 前 3 个薄弱点（掌握度 < 80）
    const weak = sorted.filter((s) => s.averageMastery < 80).slice(0, 3)

    return {
      chartData: points,
      sortedStats: sorted,
      weakPoints: weak,
      averageMastery: avg,
      cellColors: colors,
    }
  }, [data])

  const hasData = chartData.length > 0

  return (
    <ChartCardShell
      title={t("knowledgePointMastery.title")}
      description={
        hasData
          ? t("knowledgePointMastery.description", {
              count: sortedStats.length,
              avg: averageMastery.toFixed(1),
            })
          : t("knowledgePointMastery.descriptionEmpty")
      }
      icon={Brain}
      iconClassName="text-primary"
      isEmpty={!hasData}
      emptyTitle={t("knowledgePointMastery.emptyTitle")}
      emptyDescription={t("knowledgePointMastery.emptyDescription")}
      emptyClassName="h-60"
      action={
        detailHref ? (
          <Button asChild variant="ghost" size="sm">
            <Link href={detailHref}>
              {t("knowledgePointMastery.viewDetail")}
              <ArrowRight className="ml-1 h-3.5 w-3.5" aria-hidden="true" />
            </Link>
          </Button>
        ) : null
      }
    >
      {hasData ? (
        <div className="space-y-4">
          <div
            role="img"
            aria-label={t("knowledgePointMastery.ariaLabel", { count: sortedStats.length })}
          >
            <SimpleBarChart
              data={chartData}
              bars={[
                {
                  dataKey: "averageMastery",
                  name: t("knowledgePointMastery.averageMastery"),
                  color: "hsl(var(--primary))",
                },
              ]}
              xKey="label"
              yDomain={[0, 100]}
              yAllowDecimals={false}
              yTickFormatter={(value: number) => `${value}%`}
              xTickFormatter="default"
              xTruncateLength={6}
              yWidth={32}
              margin={{ left: 8, right: 8, top: 8, bottom: 8 }}
              cellColors={cellColors}
              tooltipFormatter={(payload: unknown) => {
                if (!isMasteryTooltipPayload(payload)) return null
                const item = payload.payload
                if (!item) return null
                return (
                  <div className="flex w-full flex-col gap-0.5">
                    <span className="text-sm font-medium">{item.label}</span>
                    <span className="text-xs text-muted-foreground">
                      {t("knowledgePointMastery.tooltipMastery", { score: item.averageMastery.toFixed(1) })}
                    </span>
                    <span className="text-xs text-muted-foreground">
                      {t("knowledgePointMastery.tooltipStudents", {
                        mastered: item.masteredCount,
                        total: item.totalStudents,
                      })}
                    </span>
                  </div>
                )
              }}
            />
          </div>

          {/* 薄弱知识点摘要 */}
          {weakPoints.length > 0 ? (
            <div
              className="rounded-md border border-orange-200 bg-orange-50 p-3 dark:border-orange-900 dark:bg-orange-950/30"
              role="status"
              aria-label={t("knowledgePointMastery.weakPointsAriaLabel")}
            >
              <div className="text-xs font-medium text-orange-700 dark:text-orange-300">
                {t("knowledgePointMastery.weakPointsTitle")}
              </div>
              <ul className="mt-2 space-y-1" role="list">
                {weakPoints.map((wp) => (
                  <li
                    key={wp.knowledgePointId}
                    className="flex items-center justify-between text-xs"
                    role="listitem"
                  >
                    <span className="text-foreground">{wp.knowledgePointName}</span>
                    <span
                      className={
                        wp.averageMastery < 40
                          ? "font-medium text-red-600 dark:text-red-400"
                          : wp.averageMastery < 60
                            ? "font-medium text-orange-600 dark:text-orange-400"
                            : "font-medium text-yellow-600 dark:text-yellow-400"
                      }
                    >
                      {wp.averageMastery.toFixed(1)}%
                    </span>
                  </li>
                ))}
              </ul>
            </div>
          ) : null}
        </div>
      ) : null}
    </ChartCardShell>
  )
}
