"use client";

import { useMemo } from "react";
import { useTranslations } from "next-intl";
import { AlertTriangle } from "lucide-react";
import {
  computeCurriculumCoverage,
  getHeatLevel,
  type PlanKpLink,
} from "../lib/curriculum-coverage";
import type { KnowledgePoint } from "@/modules/textbooks/types";
import { cn } from "@/shared/lib/utils";

interface Props {
  allKps: KnowledgePoint[];
  planLinks: PlanKpLink[];
  /** 章节 ID → 章节名映射 */
  chapterNames: Record<string, string>;
}

/** V5-20 T4：课标覆盖度热力图组件 */
export function CurriculumHeatmap({ allKps, planLinks, chapterNames }: Props) {
  const t = useTranslations("lessonPreparation");

  const result = useMemo(
    () => computeCurriculumCoverage(allKps, planLinks),
    [allKps, planLinks],
  );

  return (
    <div className="space-y-4">
      {/* 顶部统计条 */}
      <div className="grid grid-cols-3 gap-3">
        <StatCard
          label={t("heatmap.totalKps")}
          value={result.totalKps}
        />
        <StatCard
          label={t("heatmap.coveredKps")}
          value={result.coveredKps}
        />
        <StatCard
          label={t("heatmap.coverageRate")}
          value={`${result.overallCoverageRate}%`}
          highlight
        />
      </div>

      {/* 教学盲点警告 */}
      {result.blindSpots.length > 0 && (
        <div className="flex items-start gap-2 p-3 rounded border border-error/40 bg-error-container/30">
          <AlertTriangle className="w-4 h-4 text-error mt-0.5 flex-shrink-0" aria-hidden="true" />
          <div className="text-sm">
            <div className="font-medium text-error">
              {t("heatmap.blindSpotTitle", { count: result.blindSpots.length })}
            </div>
            <div className="text-xs text-on-surface-variant mt-1">
              {result.blindSpots.slice(0, 5).map((b) => b.kpName).join("、")}
              {result.blindSpots.length > 5 && t("heatmap.andMore")}
            </div>
          </div>
        </div>
      )}

      {/* 按章节展开的热力图 */}
      <div className="space-y-3">
        {result.chapters.map((ch) => {
          const level = getHeatLevel(ch.coverageRate);
          const chapterName = chapterNames[ch.chapterId] ?? t("heatmap.unknownChapter");
          return (
            <section key={ch.chapterId} className="border border-outline-variant rounded-lg overflow-hidden">
              {/* 章节头部带热力色块 */}
              <div className="flex items-center justify-between px-3 py-2">
                <div className="flex items-center gap-2">
                  <span
                    className={cn("inline-block w-3 h-3 rounded-sm", heatColorClass(level))}
                    aria-hidden="true"
                  />
                  <span className="font-medium text-sm">{chapterName}</span>
                </div>
                <span className="text-xs text-on-surface-variant">
                  {t("heatmap.chapterCoverage", {
                    covered: ch.coveredKps,
                    total: ch.totalKps,
                    rate: ch.coverageRate,
                  })}
                </span>
              </div>
              {/* 知识点列表 */}
              <ul className="divide-y divide-outline-variant">
                {ch.kps.map((kp) => {
                  const kpLevel = getHeatLevel(kp.planCount === 0 ? 0 : Math.min(100, kp.planCount * 33));
                  return (
                    <li
                      key={kp.kpId}
                      className="flex items-center justify-between px-3 py-1.5 text-sm"
                    >
                      <div className="flex items-center gap-2 flex-1 min-w-0">
                        <span
                          className={cn("inline-block w-2 h-2 rounded-full flex-shrink-0", heatColorClass(kpLevel))}
                          aria-hidden="true"
                        />
                        <span className="truncate">{kp.kpName}</span>
                      </div>
                      <span
                        className={cn(
                          "text-xs px-1.5 py-0.5 rounded flex-shrink-0",
                          kp.isBlindSpot
                            ? "bg-error-container/40 text-error"
                            : "bg-surface-container-highest text-on-surface-variant",
                        )}
                      >
                        {kp.isBlindSpot
                          ? t("heatmap.notCovered")
                          : t("heatmap.planCount", { count: kp.planCount })}
                      </span>
                    </li>
                  );
                })}
              </ul>
            </section>
          );
        })}
      </div>
    </div>
  );
}

function StatCard({
  label,
  value,
  highlight,
}: {
  label: string;
  value: string | number;
  highlight?: boolean;
}) {
  return (
    <div
      className={cn(
        "rounded border p-3 text-center",
        highlight
          ? "border-primary/40 bg-primary-container/20"
          : "border-outline-variant bg-surface",
      )}
    >
      <div className="text-xl font-bold">{value}</div>
      <div className="text-xs text-on-surface-variant mt-0.5">{label}</div>
    </div>
  );
}

/** 热力等级 → Tailwind 颜色类 */
function heatColorClass(level: 0 | 1 | 2 | 3 | 4): string {
  return [
    "bg-error/60",
    "bg-tertiary/40",
    "bg-tertiary/70",
    "bg-primary/60",
    "bg-primary",
  ][level];
}
