"use client";

import Link from "next/link";
import dynamic from "next/dynamic";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import type { DimensionSnapshot, TalleresSnapshot } from "@/lib/talleres/types";

const RadarChartCard = dynamic(
  () => import("@/components/app/radar-chart-card").then((module) => module.RadarChartCard),
  { ssr: false, loading: () => <div className="h-[360px] rounded-2xl border border-[#dce3ef] bg-white" /> },
);

function gapTone(gap: DimensionSnapshot["gapLevel"]) {
  if (gap === "baja") {
    return "border-[#b7e5cd] bg-[#e7f8ef] text-[#198e5f]";
  }

  if (gap === "media") {
    return "border-[#efd68d] bg-[#fff6dc] text-[#996c0f]";
  }

  return "border-[#f0c2c2] bg-[#fff0f0] text-[#a23b3b]";
}

function statusIcon(gap: DimensionSnapshot["gapLevel"]) {
  if (gap === "baja") {
    return "OK";
  }

  if (gap === "media") {
    return "!";
  }

  return "X";
}

export function DashboardMaturitySection({ snapshot }: { snapshot: TalleresSnapshot }) {
  const sortedByGap = [...snapshot.dimensions].sort((a, b) => a.displayScore - b.displayScore);
  const checklist = sortedByGap.slice(0, 3);

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <h3 className="text-2xl font-semibold text-[#142447] [font-family:var(--font-display)] md:text-3xl">Tu Indice de Madurez</h3>
          <p className="text-sm text-[#60718f]">Visualiza tu progreso hacia el siguiente nivel de preparacion.</p>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="text-center">
            <p className="text-5xl font-semibold text-[#20a777] md:text-6xl">{Math.round(snapshot.overallMaturity)}%</p>
            <p className="text-xl font-semibold text-[#213252]">Puntaje Global</p>
            <span className="mt-2 inline-flex rounded-full bg-[#24a977] px-4 py-1 text-sm font-semibold text-white">
              Nivel {snapshot.maturityLevel.label}
            </span>
          </div>

          <div className="space-y-3">
            <div className="h-4 overflow-hidden rounded-full bg-[#e2e7f1]">
              <div className="h-full bg-gradient-to-r from-[#193769] via-[#2f9a76] to-[#ddb52a]" style={{ width: `${snapshot.overallMaturity}%` }} />
            </div>
            <div className="grid grid-cols-4 gap-2 text-center text-sm">
              <p className="font-semibold text-[#4f6388]">Inicial 0%+</p>
              <p className="font-semibold text-[#4f6388]">En Desarrollo 40%+</p>
              <p className="font-semibold text-[#17386e]">Preparado 60%+</p>
              <p className="font-semibold text-[#4f6388]">Avanzado 80%+</p>
            </div>
          </div>

          <div className="rounded-2xl border border-[#d6e0ee] bg-[#f5faf7] p-4">
            <div className="flex flex-wrap items-center justify-between gap-2">
              <p className="text-2xl font-semibold text-[#18305f] md:text-3xl">
                Proximo nivel: <span className="text-[#d39b1c]">{snapshot.nextLevel?.label ?? "Avanzado"}</span>
              </p>
              {snapshot.nextLevel ? (
                <p className="text-lg font-semibold text-[#445a81]">Te faltan {snapshot.nextLevel.pointsNeeded} puntos</p>
              ) : (
                <p className="text-lg font-semibold text-[#198d62]">Ya alcanzaste el nivel maximo.</p>
              )}
            </div>
            {snapshot.nextLevel ? (
              <>
                <div className="mt-3 h-3 overflow-hidden rounded-full bg-[#d9e2ee]">
                  <div className="h-full bg-[#24a979]" style={{ width: `${snapshot.nextLevel.progressToTarget}%` }} />
                </div>
                <p className="mt-2 text-sm text-[#5e7194]">{snapshot.nextLevel.progressToTarget}% completado hacia {snapshot.nextLevel.label}</p>
              </>
            ) : null}
            <div className="mt-4 border-t border-[#dce3ef] pt-4">
              <p className="text-xl font-semibold text-[#12274d]">Para subir de nivel:</p>
              <ul className="mt-2 space-y-1 text-sm text-[#5f7293]">
                {checklist.map((dimension) => (
                  <li key={dimension.moduleKey}>- Completa talleres y evidencia en {dimension.moduleName}</li>
                ))}
              </ul>
            </div>
          </div>
        </CardContent>
      </Card>

      <div className="grid gap-4 lg:grid-cols-2">
        <Card>
          <CardHeader>
            <h3 className="text-2xl font-semibold text-[#152647] [font-family:var(--font-display)] md:text-3xl">Tu RADAR Empresarial</h3>
            <p className="text-sm text-[#60718f]">Visualiza tus fortalezas y areas de mejora en 5 dimensiones.</p>
          </CardHeader>
          <CardContent>
            <RadarChartCard
              data={snapshot.dimensions.map((dimension) => ({
                module: dimension.moduleName,
                score: Math.round(dimension.displayScore),
              }))}
            />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <h3 className="text-2xl font-semibold text-[#152647] [font-family:var(--font-display)] md:text-3xl">Puntaje por Dimension</h3>
            <p className="text-sm text-[#60718f]">Cada respuesta afirmativa suma 20 puntos. Maximo 100 por dimension.</p>
          </CardHeader>
          <CardContent className="space-y-4">
            {snapshot.dimensions.map((dimension) => (
              <article key={dimension.moduleKey} className="space-y-2">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-bold text-[#1f2f4c]">{statusIcon(dimension.gapLevel)}</span>
                    <p className="text-xl font-semibold text-[#1a2c4b] md:text-2xl">{dimension.moduleName}</p>
                    <Link href={`/talleres-desarrollo?dimension=${dimension.moduleKey}`}>
                      <Button size="sm" className="h-8 rounded-full bg-[#25a878] px-4 text-sm hover:bg-[#1f9368]">
                        Ver talleres
                      </Button>
                    </Link>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className={`rounded-full border px-3 py-1 text-sm font-semibold ${gapTone(dimension.gapLevel)}`}>{dimension.gapLabel}</span>
                    <span className="text-xl font-semibold text-[#152747]">{Math.round(dimension.displayScore)}%</span>
                  </div>
                </div>
                <div className="h-4 overflow-hidden rounded-full bg-[#d9e2ee]">
                  <div className="h-full bg-gradient-to-r from-[#19386c] to-[#24a979]" style={{ width: `${dimension.displayScore}%` }} />
                </div>
              </article>
            ))}

            <Link href="/talleres-desarrollo" className="block pt-1">
              <Button className="w-full rounded-xl bg-[#102b60] hover:bg-[#0b214b]">Ir a Talleres de Desarrollo</Button>
            </Link>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <h3 className="text-2xl font-semibold text-[#152647] [font-family:var(--font-display)] md:text-3xl">Analisis de Brechas por Dimension</h3>
          <p className="text-sm text-[#60718f]">Identificacion de riesgos asociados a cada area de tu empresa.</p>
        </CardHeader>
        <CardContent className="overflow-x-auto">
          <table className="min-w-full text-left">
            <thead>
              <tr className="border-b border-[#dce3ef] text-sm text-[#506688]">
                <th className="px-2 py-2">Dimension</th>
                <th className="px-2 py-2">Nivel actual</th>
                <th className="px-2 py-2">Brecha</th>
                <th className="px-2 py-2">Riesgo en Contratacion Publica</th>
              </tr>
            </thead>
            <tbody>
              {snapshot.dimensions.map((dimension) => (
                <tr key={dimension.moduleKey} className="border-b border-[#edf1f7] text-sm text-[#293e63]">
                  <td className="px-2 py-3 font-semibold">{dimension.moduleName}</td>
                  <td className="px-2 py-3">
                    <span className="rounded-full border border-[#d3daea] bg-[#f5f7fc] px-3 py-1 text-xs font-semibold text-[#264168]">
                      {dimension.displayScore >= 80
                        ? "Avanzado"
                        : dimension.displayScore >= 60
                          ? "Preparado"
                          : dimension.displayScore >= 40
                            ? "En Desarrollo"
                            : "Inicial"}
                    </span>
                  </td>
                  <td className="px-2 py-3">
                    <span className={`rounded-full border px-3 py-1 text-xs font-semibold ${gapTone(dimension.gapLevel)}`}>{dimension.gapLabel.replace("Brecha ", "")}</span>
                  </td>
                  <td className="px-2 py-3 text-[#5d7193]">{dimension.riskMessage}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <h3 className="text-2xl font-semibold text-[#152647] [font-family:var(--font-display)] md:text-3xl">Recomendaciones Estrategicas Generales</h3>
          <p className="text-sm text-[#60718f]">3 acciones prioritarias para mejorar tu posicion competitiva.</p>
        </CardHeader>
        <CardContent className="space-y-3">
          {snapshot.recommendations.map((recommendation, index) => (
            <article key={recommendation.id} className="rounded-2xl border border-[#d4dceb] bg-[#fdfefe] p-4">
              <p className="text-2xl font-semibold text-[#102345] md:text-3xl">
                {index + 1}. {recommendation.title}
              </p>
              <p className="mt-1 text-sm text-[#5f7395]">{recommendation.description}</p>
            </article>
          ))}
        </CardContent>
      </Card>

      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardContent className="space-y-2 py-5">
            <p className="text-2xl font-semibold text-[#132447] [font-family:var(--font-display)] md:text-3xl">Que es RADAR?</p>
            <p className="text-sm text-[#60718f]">El diagnostico RADAR evalua 5 dimensiones clave para identificar tu nivel de preparacion.</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="space-y-2 py-5">
            <p className="text-2xl font-semibold text-[#132447] [font-family:var(--font-display)] md:text-3xl">Que es CRECE?</p>
            <p className="text-sm text-[#60718f]">Es tu ruta de fortalecimiento empresarial con capacitacion, rediseno y preparacion.</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="space-y-2 py-5">
            <p className="text-2xl font-semibold text-[#132447] [font-family:var(--font-display)] md:text-3xl">Indice de Madurez</p>
            <p className="text-sm text-[#60718f]">Mide tu evolucion de Inicial a En Desarrollo, Preparado y Avanzado.</p>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
