import type { JSX } from "react";
import { getTranslations } from "next-intl/server";
import { requirePermission } from "@/shared/lib/auth-guard";
import { Permissions } from "@/shared/types/permissions";
import { getGradeOptions, getSubjectOptions } from "@/modules/school/data-access";
import { getStandardsCoverageHeatmapAction, getGlobalLessonPlanStatsAction } from "@/modules/lesson-preparation/actions-analytics";
import { CurriculumMapView } from "@/modules/lesson-preparation/components/curriculum-map-view";

export const dynamic = "force-dynamic";

export default async function CurriculumMapPage(): Promise<JSX.Element> {
  const t = await getTranslations("lessonPreparation");
  const ctx = await requirePermission(Permissions.LESSON_PLAN_READ);
  void ctx;

  const [grades, subjects, heatmapRes, statsRes] = await Promise.all([
    getGradeOptions(),
    getSubjectOptions(),
    getStandardsCoverageHeatmapAction(),
    getGlobalLessonPlanStatsAction(),
  ]);

  const heatmap = heatmapRes.success && heatmapRes.data ? heatmapRes.data.items : [];
  const stats = statsRes.success && statsRes.data ? statsRes.data.stats : null;

  return (
    <div className="p-6 space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">{t("analytics.standardsCoverage")}</h1>
        <p className="text-muted-foreground">{t("analytics.title")}</p>
      </div>

      {stats !== null && (
        <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
          <StatCard label={t("analytics.totalTeachers")} value={stats.totalTeachers} />
          <StatCard label={t("analytics.totalPlans")} value={stats.totalPlans} />
          <StatCard label={t("analytics.totalPublished")} value={stats.totalPublished} />
          <StatCard label={t("analytics.totalSubmitted")} value={stats.totalSubmitted} />
          <StatCard label={t("analytics.totalStandardsLinked")} value={stats.totalStandardsLinked} />
        </div>
      )}

      <CurriculumMapView
        grades={grades}
        subjects={subjects}
        heatmap={heatmap}
      />
    </div>
  );
}

function StatCard({ label, value }: { label: string; value: number }): JSX.Element {
  return (
    <div className="rounded-lg border p-4 bg-card">
      <p className="text-sm text-muted-foreground">{label}</p>
      <p className="text-2xl font-bold mt-1">{value}</p>
    </div>
  );
}