import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { getSiteConfig, isMercadoPagoEnabled, isPaykuEnabled } from "@/lib/site-config";
import { isPaykuConfigured, isPaykuSandbox } from "@/lib/payku";
import AdminPaymentSettings from "@/components/AdminPaymentSettings";
import AdminStickerDiscountSettings from "@/components/AdminStickerDiscountSettings";
import { getMailProvider, getEmailLog } from "@/lib/mail";
import {
  Activity, CheckCircle2, AlertTriangle, XCircle, ArrowRight,
} from "lucide-react";

export const dynamic = "force-dynamic";

type Level = "ok" | "warn" | "error";

type Check = {
  section: string;
  href: string;
  status: Level;
  detail: string;
};

function levelStyles(level: Level) {
  switch (level) {
    case "ok":
      return { icon: CheckCircle2, color: "text-green-400", ring: "border-green-500/30 bg-green-500/5" };
    case "warn":
      return { icon: AlertTriangle, color: "text-amber-400", ring: "border-amber-500/30 bg-amber-500/5" };
    case "error":
      return { icon: XCircle, color: "text-red-400", ring: "border-red-500/30 bg-red-500/5" };
  }
}

async function buildChecks(): Promise<Check[]> {
  const checks: Check[] = [];

  // 1. Base de datos
  let dbOk = false;
  try {
    await prisma.$queryRaw`SELECT 1`;
    dbOk = true;
  } catch {
    dbOk = false;
  }
  checks.push({
    section: "Base de datos",
    href: "/admin",
    status: dbOk ? "ok" : "error",
    detail: dbOk ? "Conexión activa" : "No se pudo conectar a PostgreSQL",
  });

  if (!dbOk) return checks;

  // Cargas en paralelo
  const [
    config,
    ticketProducts,
    physicalProducts,
    carouselCount,
    watermarkCount,
    activePromos,
    ordersPaid,
    ordersPending,
    standCount,
    admins,
    lastLogin,
    auditCount,
  ] = await Promise.all([
    getSiteConfig(),
    prisma.product.count({ where: { type: "TICKET" } }),
    prisma.product.count({ where: { type: "PHYSICAL" } }),
    prisma.carouselSlide.count(),
    prisma.watermarkSlide.count(),
    prisma.promo.count({ where: { active: true } }),
    prisma.order.count({ where: { status: "PAID" } }),
    prisma.order.count({ where: { status: "PENDING" } }),
    prisma.standRegistration.count(),
    prisma.user.count({ where: { role: "ADMIN" } }),
    prisma.adminLoginLog.findFirst({ orderBy: { createdAt: "desc" } }),
    prisma.adminLog.count(),
  ]);

  // 2. Correo
  const provider = getMailProvider();
  const lastEmail = getEmailLog()[0];
  checks.push({
    section: "Correo (envíos)",
    href: "/admin/email-preview",
    status: provider === "none" ? "error" : lastEmail && !lastEmail.ok ? "warn" : "ok",
    detail:
      provider === "none"
        ? "Sin proveedor configurado (Resend/SMTP)"
        : `Proveedor: ${provider.toUpperCase()}${lastEmail ? ` · último envío ${lastEmail.ok ? "OK" : "FALLÓ"}` : " · sin envíos aún"}`,
  });

  // 3. Pagos - Mercado Pago
  const mpOk = Boolean(process.env.MERCADOPAGO_ACCESS_TOKEN);
  checks.push({
    section: "Pago: Mercado Pago",
    href: "/admin/orders",
    status: mpOk ? "ok" : "error",
    detail: mpOk
      ? `Credenciales presentes${
          process.env.MP_WEBHOOK_SECRET
            ? process.env.MP_WEBHOOK_SECRET.startsWith("TEST-")
              ? " · ⚠ webhook secret parece de TEST"
              : " · webhook firmado"
            : " · sin secreto de webhook"
        }`
      : "Falta MERCADOPAGO_ACCESS_TOKEN en .env",
  });

  // 4. Pagos - Flow
  const flowOk = Boolean(process.env.FLOW_API_KEY && process.env.FLOW_SECRET_KEY);
  const flowSandbox = (process.env.FLOW_API_URL || "").includes("sandbox");
  checks.push({
    section: "Pago: Flow",
    href: "/admin/orders",
    status: flowOk ? (flowSandbox ? "warn" : "ok") : "warn",
    detail: flowOk
      ? flowSandbox
        ? "Configurado en modo SANDBOX (pruebas)"
        : "Configurado en producción"
      : "Sin credenciales Flow (opcional si usas solo Mercado Pago / Payku)",
  });

  // 4b. Pagos - Payku
  const paykuOk = isPaykuConfigured();
  const paykuUiOn = isPaykuEnabled(config);
  checks.push({
    section: "Pago: Payku",
    href: "/admin/estado",
    status: !paykuUiOn ? "warn" : paykuOk ? (isPaykuSandbox() ? "warn" : "ok") : "error",
    detail: !paykuUiOn
      ? "Botón desactivado en la tienda"
      : paykuOk
        ? isPaykuSandbox()
          ? "Modo SANDBOX (des.payku.cl)"
          : "Producción (app.payku.cl)"
        : "Botón activo pero falta PAYKU_PUBLIC_TOKEN en .env",
  });

  // 4c. Botón Mercado Pago en tienda
  const mpUiOn = isMercadoPagoEnabled(config);
  checks.push({
    section: "Botón Mercado Pago",
    href: "/admin/estado",
    status: mpUiOn ? "ok" : "warn",
    detail: mpUiOn ? "Visible en el carrito" : "Desactivado en la tienda",
  });

  // 5. Productos / Tickets
  checks.push({
    section: "Láminas / Tickets",
    href: "/admin/products",
    status: ticketProducts > 0 ? "ok" : "warn",
    detail: ticketProducts > 0 ? `${ticketProducts} producto(s) de tickets` : "No hay productos de tickets creados",
  });

  // 6. Tienda / Merch
  const merchEnabled = config.merch_enabled === "true";
  checks.push({
    section: "Tienda / Merch",
    href: "/admin/merch",
    status: !merchEnabled ? "warn" : physicalProducts > 0 ? "ok" : "warn",
    detail: !merchEnabled
      ? "Tienda desactivada"
      : physicalProducts > 0
        ? `Activada · ${physicalProducts} producto(s) físicos`
        : "Activada pero sin productos físicos",
  });

  // 7. Carrusel portada
  checks.push({
    section: "Carrusel portada",
    href: "/admin/carousel",
    status: carouselCount > 0 ? "ok" : "warn",
    detail: carouselCount > 0 ? `${carouselCount} imagen(es)` : "Sin imágenes (usa la imagen única del sitio)",
  });

  // 8. Contenido del sitio
  const heroSet = !!config.hero_image?.trim();
  checks.push({
    section: "Contenido del sitio",
    href: "/admin/site-images",
    status: heroSet ? "ok" : "warn",
    detail: heroSet ? "Foto del premio cargada" : "Sin foto del premio (se muestra un degradado)",
  });

  // 9. Marcas de agua
  checks.push({
    section: "Marcas de agua",
    href: "/admin/watermarks",
    status: "ok",
    detail: `${watermarkCount} imagen(es)`,
  });

  // 10. Promociones
  checks.push({
    section: "Promociones",
    href: "/admin/promos",
    status: activePromos > 0 ? "ok" : "warn",
    detail: activePromos > 0 ? `${activePromos} promo(s) activa(s)` : "Sin promociones activas",
  });

  // 11. Pedidos
  checks.push({
    section: "Pedidos & Tickets",
    href: "/admin/orders",
    status: "ok",
    detail: `${ordersPaid} pagado(s) · ${ordersPending} pendiente(s)`,
  });

  // 12. Stand / QR
  const standEnabled = config.stand_enabled === "true";
  checks.push({
    section: "Stand / QR",
    href: "/admin/stand",
    status: standEnabled ? "ok" : "warn",
    detail: standEnabled ? `Activado · ${standCount} registro(s)` : "Desactivado",
  });

  // 13. Resultados del sorteo
  const resultsEnabled = config.draw_results_enabled === "true";
  checks.push({
    section: "Resultados del sorteo",
    href: "/admin/site-images",
    status: resultsEnabled ? "ok" : "warn",
    detail: resultsEnabled ? "Sección de ganadores visible" : "Sección de ganadores oculta",
  });

  // 14. Seguridad / 2FA
  const admins2fa = await prisma.user.count({ where: { role: "ADMIN", isTwoFactorEnabled: true } });
  checks.push({
    section: "Seguridad (2FA)",
    href: "/admin/security",
    status: admins2fa > 0 ? "ok" : "warn",
    detail: `${admins}${admins === 1 ? " admin" : " admins"} · ${admins2fa} con 2FA activo`,
  });

  // 15. Accesos admin
  checks.push({
    section: "Accesos admin",
    href: "/admin/access-log",
    status: lastLogin ? "ok" : "warn",
    detail: lastLogin
      ? `Último acceso: ${lastLogin.createdAt.toLocaleString("es-CL")}`
      : "Sin accesos registrados",
  });

  // 16. Auditoría
  checks.push({
    section: "Registro de auditoría",
    href: "/admin/logs",
    status: "ok",
    detail: `${auditCount} evento(s) registrados`,
  });

  return checks;
}

export default async function AdminEstadoPage() {
  const config = await getSiteConfig();
  const checks = await buildChecks();
  const counts = {
    ok: checks.filter((c) => c.status === "ok").length,
    warn: checks.filter((c) => c.status === "warn").length,
    error: checks.filter((c) => c.status === "error").length,
  };

  return (
    <div className="space-y-8">
      <div className="flex items-center justify-between gap-4 flex-wrap">
        <div className="flex items-center gap-3">
          <Activity className="text-[#7c3aed] w-7 h-7" />
          <h1 className="text-3xl font-bold">Estado del sistema</h1>
        </div>
        <div className="flex items-center gap-3 text-sm">
          <span className="flex items-center gap-1.5 text-green-400">
            <CheckCircle2 className="w-4 h-4" /> {counts.ok} OK
          </span>
          <span className="flex items-center gap-1.5 text-amber-400">
            <AlertTriangle className="w-4 h-4" /> {counts.warn} avisos
          </span>
          <span className="flex items-center gap-1.5 text-red-400">
            <XCircle className="w-4 h-4" /> {counts.error} errores
          </span>
        </div>
      </div>

      <p className="text-gray-400 text-sm max-w-2xl">
        Diagnóstico rápido de cada funcionalidad del panel. Verde = correcto, amarillo = revisar
        (opcional o incompleto), rojo = requiere acción. Haz clic en cualquier tarjeta para ir a su
        sección.
      </p>

      <AdminPaymentSettings
        initialMercadoPago={isMercadoPagoEnabled(config)}
        initialPayku={isPaykuEnabled(config)}
      />

      <AdminStickerDiscountSettings
        initialPercent={parseInt(config.sticker_discount_percent || "0", 10) || 0}
        initialEndAtIso={config.sticker_discount_end_at || ""}
      />

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {checks.map((c) => {
          const s = levelStyles(c.status);
          const Icon = s.icon;
          return (
            <Link
              key={c.section}
              href={c.href}
              className={`group flex items-start gap-3 p-4 rounded-xl border transition-colors hover:bg-white/[0.06] ${s.ring}`}
            >
              <Icon className={`w-5 h-5 shrink-0 mt-0.5 ${s.color}`} />
              <div className="flex-1 min-w-0">
                <div className="flex items-center justify-between gap-2">
                  <p className="font-semibold text-white">{c.section}</p>
                  <ArrowRight className="w-4 h-4 text-gray-600 group-hover:text-white transition-colors shrink-0" />
                </div>
                <p className="text-sm text-gray-400 mt-0.5">{c.detail}</p>
              </div>
            </Link>
          );
        })}
      </div>
    </div>
  );
}
