import Link from "next/link";
import type { ModulePlanKey } from "@prisma/client";
import { isAdminIdentity } from "@/lib/auth/admin";
import { getActivePlanKeysForUser } from "@/lib/auth/module-access";
import { PageShell } from "@/components/app/page-shell";
import { DashboardMaturitySection } from "@/components/app/dashboard-maturity-section";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { requireOnboardedUser } from "@/lib/auth/user";
import { hasMercadoPagoConfig } from "@/lib/payments/mercadopago";
import { getModulePlanByUiKey } from "@/lib/payments/plans";
import { cn } from "@/lib/utils";
import { recomputeAssessmentResults } from "@/lib/scoring";
import { getTalleresSnapshot } from "@/lib/talleres/server";

type PlanModule = {
  id: string;
  title: string;
  description: string;
  href?: string;
};

type PlanGroup = {
  key: string;
  name: string;
  price: string;
  benefits: string;
  dotClassName: string;
  frameClassName: string;
  badgeClassName: string;
  moduleToneClassName: string;
  iconToneClassName: string;
  modules: PlanModule[];
};

const planGroups: PlanGroup[] = [
  {
    key: "plan-1",
    name: "Plan 1",
    price: "$499 MXN/mes",
    benefits: "2 usuarios - 50 creditos IA",
    dotClassName: "bg-[#3e7fe6]",
    frameClassName: "border-[#82b0ef] bg-[#edf4ff]",
    badgeClassName: "border-[#bdd2f3] bg-[#e8f1ff] text-[#4d6993]",
    moduleToneClassName: "border-[#c8d7ee]",
    iconToneClassName: "bg-[#d8e7ff] text-[#3b74d2]",
    modules: [
      {
        id: "M02",
        title: "Perfil Competitivo",
        description: "Construye tu perfil estrategico detallado para aumentar tu compatibilidad.",
        href: "/strategic-diagnostic",
      },
      {
        id: "M03",
        title: "Deteccion de Oportunidades",
        description: "Encuentra licitaciones compatibles con tu perfil de forma automatica.",
        href: "/licitations",
      },
      {
        id: "M04",
        title: "Analisis Normativo",
        description: "Analiza las bases de licitacion que te interesen con IA.",
        href: "/normative-analysis",
      },
    ],
  },
  {
    key: "plan-2",
    name: "Plan 2",
    price: "$999 MXN/mes",
    benefits: "5 usuarios - 150 creditos IA",
    dotClassName: "bg-[#9f63ea]",
    frameClassName: "border-[#c8a8f1] bg-[#f6f0ff]",
    badgeClassName: "border-[#dbcaf2] bg-[#f1e9ff] text-[#6a5492]",
    moduleToneClassName: "border-[#d7c8ec]",
    iconToneClassName: "bg-[#ecdfff] text-[#8f52d8]",
    modules: [
      {
        id: "M05",
        title: "Gestion Integral de Licitaciones",
        description: "Herramienta completa para preparar, revisar y enviar propuestas con checklist.",
        href: "/gestion-licitaciones",
      },
      {
        id: "M06",
        title: "Detector de Candados y Riesgos",
        description: "Analisis automatico de bases para identificar requisitos excluyentes o riesgos.",
        href: "/candados",
      },
      {
        id: "M07",
        title: "Alertas de Cumplimiento",
        description: "Notificaciones proactivas sobre plazos, documentos vencidos y cambios normativos.",
        href: "/compliance-alerts",
      },
    ],
  },
  {
    key: "plan-3",
    name: "Plan 3",
    price: "$1,999 MXN/mes",
    benefits: "Usuarios ilimitados - 500 creditos IA",
    dotClassName: "bg-[#e6a61d]",
    frameClassName: "border-[#e4c06f] bg-[#fff7e8]",
    badgeClassName: "border-[#edd7a7] bg-[#fff4dc] text-[#8a6b28]",
    moduleToneClassName: "border-[#ecdab0]",
    iconToneClassName: "bg-[#ffefcd] text-[#cf9420]",
    modules: [
      {
        id: "M08",
        title: "Gestion Estrategica de Contratos",
        description: "Dashboard para administrar contratos activos, entregables y pagos.",
        href: "/gestion-contratos",
      },
      {
        id: "M09",
        title: "Proteccion Legal",
        description: "Guia legal y plantillas ante incumplimientos, retenciones o sanciones.",
        href: "/proteccion-legal",
      },
      {
        id: "M10",
        title: "Simulador de Auditorias",
        description: "Autoevaluacion que prepara a tu empresa para auditorias gubernamentales.",
        href: "/expediente-preventivo",
      },
    ],
  },
];

function getReadinessLabel(score: number) {
  if (score >= 80) {
    return "Lider";
  }

  if (score >= 60) {
    return "Preparado";
  }

  if (score >= 40) {
    return "En Desarrollo";
  }

  return "Inicial";
}

function getReadinessDescription(score: number) {
  if (score >= 80) {
    return "Tu empresa muestra capacidades avanzadas para competir en contratacion publica.";
  }

  if (score >= 60) {
    return "Tu empresa tiene bases solidas para participar en contratacion publica con exito.";
  }

  if (score >= 40) {
    return "Tu empresa avanza bien, pero requiere reforzar capacidades clave para escalar resultados.";
  }

  return "Tu empresa requiere fortalecer fundamentos antes de competir en licitaciones complejas.";
}

function LockIcon({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 24 24" className={className} aria-hidden>
      <path
        d="M7 10V8a5 5 0 0 1 10 0v2m-8 0h6m-9 0h12a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1v-8a1 1 0 0 1 1-1Z"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

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

function getParam(params: Record<string, string | string[] | undefined>, key: string) {
  const value = params[key];
  return Array.isArray(value) ? value[0] ?? "" : (value ?? "");
}

export default async function DashboardPage({ searchParams }: DashboardPageProps) {
  const user = await requireOnboardedUser();
  const snapshot = await recomputeAssessmentResults(user.id);
  const talleresSnapshot = await getTalleresSnapshot(user.id, { assessmentSnapshot: snapshot });
  const isAdminUser = isAdminIdentity(user.email, user.role);
  const activePlanKeys = isAdminUser
    ? new Set<ModulePlanKey>(["PLAN_2_4", "PLAN_5_7", "PLAN_8_10"])
    : await getActivePlanKeysForUser(user.id);
  const hasPaidModulesAccess = activePlanKeys.size > 0;
  const paymentConfigured = hasMercadoPagoConfig();
  const resolvedSearchParams = await searchParams;
  const checkoutResult = getParam(resolvedSearchParams, "mp_result");
  const checkoutError = getParam(resolvedSearchParams, "mp_error");
  const roundedOverallScore = Math.round(snapshot.overallScore);
  const readinessLabel = getReadinessLabel(roundedOverallScore);
  const strongest = snapshot.strongestModule;
  const weakest = snapshot.weakestModule;

  return (
    <PageShell
      title="Dashboard"
      description="Resumen ejecutivo y acceso a la ruta de modulos."
      className="space-y-6"
      action={
        <Link href="/diagnostic">
          <Button size="sm">Ir al diagnostico</Button>
        </Link>
      }
    >
      <section className="rounded-2xl border border-[#dce3ef] bg-[#f2f6fc] px-4 py-4">
        <div className="flex flex-wrap items-center justify-center gap-x-8 gap-y-3 text-base font-medium text-[#4a5f84]">
          <span className="inline-flex items-center gap-2">
            <span className="h-3.5 w-3.5 rounded-full bg-[#23498f]" />
            RADAR - Diagnostico
          </span>
          <span className="inline-flex items-center gap-2">
            <span className="h-3.5 w-3.5 rounded-full bg-[#29a67a]" />
            CRECE - Acompanamiento
          </span>
          <span className="inline-flex items-center gap-2">
            <span className="h-3.5 w-3.5 rounded-full bg-[#dfb11e]" />
            INDICE - Medicion
          </span>
        </div>
        <div className="mt-4 flex flex-wrap items-center justify-center gap-3 text-sm">
          <span className="rounded-full border border-[#abdbc5] bg-[#dff4e9] px-4 py-1.5 font-semibold text-[#269f75]">GRATIS Modulo 1</span>
          <span className="rounded-full border border-[#b8d0ef] bg-[#dce6f8] px-4 py-1.5 font-semibold text-[#2f5eda]">Plan 1 Modulos 2-4</span>
          <span className="rounded-full border border-[#d2beee] bg-[#e8ddf6] px-4 py-1.5 font-semibold text-[#8444d0]">Plan 2 Modulos 5-7</span>
          <span className="rounded-full border border-[#e0cc9e] bg-[#f4ead4] px-4 py-1.5 font-semibold text-[#d2840d]">Plan 3 Modulos 8-10</span>
        </div>
      </section>

      <Card className="border-[#a8dbc8]">
        <CardContent className="py-8">
          <div className="mx-auto max-w-4xl text-center">
            <span className="inline-flex rounded-full bg-[#24aa77] px-7 py-2 text-xl font-semibold text-white">Nivel {readinessLabel}</span>
            <h2 className="mt-6 text-3xl font-semibold text-[#0f2142] [font-family:var(--font-display)] md:text-4xl">
              Puntaje Global: {roundedOverallScore}%
            </h2>
            <p className="mx-auto mt-4 max-w-3xl text-xl leading-relaxed text-[#4d6285] md:text-2xl">
              {getReadinessDescription(roundedOverallScore)}
            </p>

            <div className="mt-8 grid gap-4 md:grid-cols-2">
              <article className="rounded-2xl border border-[#abd9c8] bg-[#e9f5ef] px-5 py-5 text-left">
                <p className="inline-flex items-center gap-2 text-sm font-semibold uppercase tracking-[0.08em] text-[#1e8f67]">
                  <span className="inline-flex h-5 w-5 items-center justify-center rounded-full border border-[#54b88f] text-xs">v</span>
                  Principal Fortaleza
                </p>
                <h3 className="mt-2 text-2xl font-semibold text-[#139768]">
                  {strongest ? strongest.moduleName : "Aun sin datos suficientes"}
                </h3>
                <p className="mt-1 text-base text-[#4e6b65]">{strongest ? `${Math.round(strongest.score)}% de madurez` : "Responde el diagnostico para calcular."}</p>
              </article>

              <article className="rounded-2xl border border-[#efbdc3] bg-[#fff0f2] px-5 py-5 text-left">
                <p className="inline-flex items-center gap-2 text-sm font-semibold uppercase tracking-[0.08em] text-[#d14c59]">
                  <span className="inline-flex h-5 w-5 items-center justify-center rounded-full border border-[#ef7b86] text-xs">!</span>
                  Area Critica de Mejora
                </p>
                <h3 className="mt-2 text-2xl font-semibold text-[#e14658]">
                  {weakest ? weakest.moduleName : "Aun sin datos suficientes"}
                </h3>
                <p className="mt-1 text-base text-[#7a5b63]">{weakest ? `${Math.round(weakest.score)}% de madurez` : "Responde el diagnostico para calcular."}</p>
              </article>
            </div>
          </div>
        </CardContent>
      </Card>

      <section id="modulos" className="space-y-4">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <h2 className="text-2xl font-semibold text-[#1a2b48] [font-family:var(--font-display)] md:text-3xl">Modulos y planes</h2>
            <p className="mt-1 text-sm text-[#5f7293]">Ruta de crecimiento: Modulo 1 (gratis) + Modulos 2-10 por suscripcion.</p>
          </div>
          <span className={cn("inline-flex items-center gap-2 rounded-full border px-4 py-1.5 text-sm font-semibold", hasPaidModulesAccess ? "border-[#a9d8c8] bg-[#e8f6ef] text-[#1e8f67]" : "border-[#d7dceb] bg-[#eff3fb] text-[#5a6b88]")}>
            {hasPaidModulesAccess ? "Plan con acceso activo" : "Cuenta en plan gratuito"}
          </span>
        </div>

        {checkoutResult ? (
          <div className={cn("rounded-xl border px-4 py-3 text-sm", checkoutResult === "success" ? "border-[#a9d8c8] bg-[#ecf9f2] text-[#1f8b63]" : "border-[#e7d7ac] bg-[#fff8ea] text-[#8b6b1f]")}>
            {checkoutResult === "success"
              ? "Mercado Pago reporto checkout exitoso. Estamos validando tu pago y activando el plan."
              : checkoutResult === "failure"
                ? "El pago no se completo. Puedes intentarlo nuevamente."
                : "Tu pago esta pendiente de confirmacion. Te avisaremos cuando se active el plan."}
          </div>
        ) : null}

        {checkoutError ? (
          <div className="rounded-xl border border-[#f1c7cc] bg-[#fff1f3] px-4 py-3 text-sm text-[#a03d4b]">
            No fue posible iniciar el checkout ({checkoutError}). Verifica la configuracion de Mercado Pago.
          </div>
        ) : null}

        <Card className="border-[#a9d9c7] bg-[#f3fbf7]">
          <CardContent className="flex flex-wrap items-center justify-between gap-3 py-4">
            <div>
              <p className="text-sm font-semibold uppercase tracking-[0.08em] text-[#249f74]">Modulo 1 gratuito</p>
              <h3 className="mt-1 text-xl font-semibold text-[#17315a]">Diagnostico RADAR Inicial</h3>
              <p className="mt-1 text-sm text-[#5d6f8e]">Este modulo siempre esta disponible para todos los usuarios.</p>
            </div>
            <Link href="/diagnostic">
              <Button size="sm" className="rounded-xl bg-[#24a977] hover:bg-[#1d9368]">
                Ir a Diagnostico
              </Button>
            </Link>
          </CardContent>
        </Card>

        {planGroups.map((group) => (
          <article key={group.key} className={cn("rounded-2xl border p-3 md:p-4", group.frameClassName)}>
            {(() => {
              const plan = getModulePlanByUiKey(group.key);
              const planActive = plan ? activePlanKeys.has(plan.key) : false;
              return (
                <>
            <header className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-white/60 bg-white/50 px-3 py-2">
              <div className="flex items-start gap-3">
                <span className={cn("mt-1.5 h-3 w-3 rounded-full", group.dotClassName)} />
                <div>
                  <p className="text-2xl font-semibold text-[#102041] [font-family:var(--font-display)]">
                    {group.name} - {group.price}
                  </p>
                  <p className="text-sm text-[#576d8f]">{group.benefits}</p>
                </div>
              </div>

              <span className={cn("inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-sm font-semibold", group.badgeClassName)}>
                <LockIcon className="h-4 w-4" />
                {planActive ? "Disponible" : "Bloqueado"}
              </span>
            </header>

            <div className="mt-3 grid gap-3 md:grid-cols-3">
              {group.modules.map((moduleItem) => {
                const isLocked = !planActive || !moduleItem.href;

                return (
                  <article
                    key={moduleItem.id}
                    className={cn(
                      "rounded-2xl border bg-white p-4 shadow-[0_1px_2px_rgba(16,24,40,0.04)] transition",
                      group.moduleToneClassName,
                      isLocked ? "opacity-55 grayscale-[20%]" : "hover:-translate-y-0.5",
                    )}
                  >
                    <div className="flex items-start justify-between gap-2">
                      <span className={cn("inline-flex h-10 w-10 items-center justify-center rounded-xl text-xs font-bold", group.iconToneClassName)}>
                        {moduleItem.id}
                      </span>
                      <span className="rounded-full border border-[#e5eaf4] bg-[#f7f9fc] px-3 py-0.5 text-xs font-semibold text-[#6d7f9c]">
                        {moduleItem.id}
                      </span>
                    </div>

                    <h4 className="mt-4 text-lg font-semibold text-[#20304d]">{moduleItem.title}</h4>
                    <p className="mt-2 text-sm leading-relaxed text-[#6b7891]">{moduleItem.description}</p>

                    <div className="mt-4">
                      {isLocked ? (
                        <span className="inline-flex items-center gap-2 rounded-full border border-[#d8dfea] bg-[#eef2f8] px-3 py-1 text-sm font-semibold text-[#64738c]">
                          <LockIcon className="h-4 w-4" />
                          Bloqueado
                        </span>
                      ) : (
                        <Link href={moduleItem.href as string}>
                          <Button size="sm" className="rounded-xl">
                            Ir al modulo
                          </Button>
                        </Link>
                      )}
                    </div>
                  </article>
                );
              })}
            </div>
            {!planActive ? (
              <div className="mt-3 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-white/70 bg-white/55 px-3 py-3">
                <p className="text-sm text-[#5a6f90]">
                  Desbloquea Modulos {plan?.moduleStart}-{plan?.moduleEnd} con {group.name}.
                </p>
                {paymentConfigured ? (
                  <Link href={`/api/payments/checkout?plan=${encodeURIComponent(group.key)}`}>
                    <Button size="sm" className="rounded-xl">
                      Comprar {group.name}
                    </Button>
                  </Link>
                ) : (
                  <span className="rounded-full border border-[#d8dfea] bg-[#eef2f8] px-3 py-1 text-xs font-semibold text-[#64738c]">
                    Configura `MP_ACCESS_TOKEN`
                  </span>
                )}
              </div>
            ) : null}
          </>
              );
            })()}
          </article>
        ))}

        <div className="rounded-2xl border border-dashed border-[#d4dceb] bg-[#f8fbff] px-5 py-5 text-center">
          <p className="text-sm font-semibold uppercase tracking-[0.08em] text-[#607290]">Ruta de expansion</p>
          <p className="mt-2 text-base text-[#536a8e]">Actualmente la plataforma contempla 10 modulos.</p>
          <Link href="/#planes" className="mt-4 inline-flex">
            <Button size="sm" className="rounded-xl bg-[#e1af1c] text-[#243351] hover:bg-[#cf9f16]">
              Ver todos los planes
            </Button>
          </Link>
        </div>

        <DashboardMaturitySection snapshot={talleresSnapshot} />
      </section>
    </PageShell>
  );
}
