import Link from "next/link";
import { hasAnyPaidModuleAccess } from "@/lib/auth/module-access";
import { requireOnboardedUser } from "@/lib/auth/user";
import { PageShell } from "@/components/app/page-shell";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { TalleresDesarrolloView } from "@/components/app/talleres-desarrollo-view";
import { getTalleresSnapshot } from "@/lib/talleres/server";

type PageProps = {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
};

function parseDimension(searchParams: Record<string, string | string[] | undefined>) {
  const rawValue = searchParams.dimension;

  if (typeof rawValue === "string") {
    return rawValue.trim() || null;
  }

  if (Array.isArray(rawValue)) {
    return rawValue[0]?.trim() || null;
  }

  return null;
}

export default async function TalleresDesarrolloPage({ searchParams }: PageProps) {
  const user = await requireOnboardedUser();
  const hasPaidModulesAccess = await hasAnyPaidModuleAccess(user.id, user.email, user.role);

  if (!hasPaidModulesAccess) {
    return (
      <PageShell
        title="Talleres de Desarrollo"
        description="Ruta premium para cerrar brechas por dimension con cursos especializados."
        action={<span className="rounded-full border border-[#d5ddec] bg-[#edf2fb] px-4 py-1 text-sm font-semibold text-[#5a6a87]">Bloqueado</span>}
      >
        <Card>
          <CardHeader>
            <h2 className="text-lg font-semibold text-[#1f2a40]">Acceso restringido</h2>
          </CardHeader>
          <CardContent className="space-y-3">
            <p className="text-sm text-[#64718a]">Talleres de Desarrollo forma parte de la ruta premium de modulos pagados.</p>
            <div className="flex flex-wrap gap-2">
              <Link href="/dashboard#modulos">
                <Button>Ver modulos y planes</Button>
              </Link>
              <Link href="/strategic-diagnostic">
                <Button variant="secondary">Ir a Modulo 2</Button>
              </Link>
            </div>
          </CardContent>
        </Card>
      </PageShell>
    );
  }

  const resolvedSearchParams = await searchParams;
  const selectedDimension = parseDimension(resolvedSearchParams);
  const snapshot = await getTalleresSnapshot(user.id);

  return (
    <PageShell
      title="Talleres de Desarrollo"
      description="Treisole - Cubre tus brechas con cursos especializados"
      action={<span className="rounded-full bg-[#0f2a5f] px-4 py-1 text-sm font-semibold text-white">Plan Activo</span>}
      className="space-y-6"
    >
      <TalleresDesarrolloView initialSnapshot={snapshot} initialDimension={selectedDimension} />
    </PageShell>
  );
}
