import { notFound } from "next/navigation";
import { ModuleQuestionnaire } from "@/components/app/module-questionnaire";
import { PageShell } from "@/components/app/page-shell";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { requireOnboardedUser } from "@/lib/auth/user";
import { getDiagnosticModuleQuestions, getDiagnosticOverview } from "@/lib/diagnostic";

type ModuleQuestionPageProps = {
  params: Promise<{ moduleId: string }>;
};

export default async function ModuleQuestionPage({ params }: ModuleQuestionPageProps) {
  const user = await requireOnboardedUser();
  const { moduleId } = await params;

  const moduleData = await getDiagnosticModuleQuestions(user.id, moduleId);
  const overview = await getDiagnosticOverview(user.id);

  if (!moduleData) {
    notFound();
  }

  const currentModuleIndex = overview.modules.findIndex((module) => module.key === moduleData.module.key);
  const previousModule = currentModuleIndex > 0 ? overview.modules[currentModuleIndex - 1] : null;
  const nextModule = currentModuleIndex >= 0 && currentModuleIndex < overview.modules.length - 1 ? overview.modules[currentModuleIndex + 1] : null;

  return (
    <PageShell
      title={`Modulo: ${moduleData.module.name}`}
      description={moduleData.module.description ?? "Responde cada pregunta para calcular el puntaje por modulo."}
    >
      {moduleData.questions.length === 0 ? (
        <Card>
          <CardHeader>
            <h2 className="text-lg font-semibold text-[#1f2a40]">No hay preguntas configuradas</h2>
          </CardHeader>
          <CardContent>
            <p className="text-sm text-[#64718a]">
              Este modulo aun no contiene preguntas. Regresa al listado e intenta con otro modulo.
            </p>
          </CardContent>
        </Card>
      ) : (
        <ModuleQuestionnaire
          moduleKey={moduleData.module.key}
          moduleName={moduleData.module.name}
          moduleDescription={moduleData.module.description}
          questions={moduleData.questions}
          moduleTabs={overview.modules.map((module) => ({
            key: module.key,
            label: module.name,
            href: `/diagnostic/${module.key}`,
            active: module.key === moduleData.module.key,
          }))}
          previousModuleHref={previousModule ? `/diagnostic/${previousModule.key}` : null}
          nextModuleHref={nextModule ? `/diagnostic/${nextModule.key}` : null}
          isLastModule={currentModuleIndex >= 0 && currentModuleIndex === overview.modules.length - 1}
        />
      )}
    </PageShell>
  );
}
