import type { Metadata } from "next";
import React from "react";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth";
import Link from "next/link";
import { db } from "@/lib/db";
import { curso, clase } from "@/db/schema";
import { eq, and } from "drizzle-orm";
import { getDashboardInscripciones } from "@/lib/mariadb-relations";
import { redirect } from "next/navigation";

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  title: "Panel de Administración | CursosNirgua",
  description: "Panel Administrativo Multi-Usuario",
};

export default async function AdminDashboard() {
  const session = await getServerSession(authOptions);

  if (!session || (session.user.role !== "SUPERADMIN" && session.user.role !== "ADMIN_COLEGIO")) {
    redirect("/api/auth/signin");
  }

  const colegioId = session.user.role === "ADMIN_COLEGIO" && session.user.colegioId
    ? session.user.colegioId
    : null;

  // Contar cursos activos
  const cursosAll = await db.query.curso.findMany({
    where: colegioId
      ? and(eq(curso.activo, true), eq(curso.colegioId, colegioId))
      : eq(curso.activo, true),
    columns: { id: true }
  });
  const totalCursos = cursosAll.length;

  const cursoIds = cursosAll.map(c => c.id);

  // Inscripciones filtradas por los cursos del colegio
  const todasInscripciones = cursoIds.length > 0
    ? await getDashboardInscripciones()
    : [];

  const inscripcionesFiltradas = colegioId
    ? todasInscripciones.filter(ins => ins.curso?.colegioId === colegioId)
    : todasInscripciones;

  const pagosAprobados  = inscripcionesFiltradas.filter(i => i.estadoPago === "APROBADO").length;
  const pagosPendientes = inscripcionesFiltradas.filter(i => i.estadoPago === "PENDIENTE").length;
  const pagosRechazados = inscripcionesFiltradas.filter(i => i.estadoPago === "RECHAZADO").length;

  // Horas dictadas
  const clasesData = await db.query.clase.findMany({
    where: colegioId
      ? and(eq(clase.colegioId, colegioId), eq(clase.estado, "DICTADA"))
      : eq(clase.estado, "DICTADA"),
    columns: { horasDadas: true }
  });
  const totalHorasDadas = clasesData.reduce((acc, c) => acc + (c.horasDadas || 0), 0);

  // Inscripciones recientes (últimas 5)
  const inscripcionesRecientes = inscripcionesFiltradas
    .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
    .slice(0, 5);

  return (
    <div className="flex flex-col gap-6">
      
      {/* Header Panel */}
      <div className="bg-white p-6 shadow-sm rounded-xl border border-gray-100 flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-extrabold text-gray-800 tracking-tight">
            Panel de Administración - {session.user.role === 'SUPERADMIN' || session.user.role === 'ADMIN_COLEGIO' ? 'Master' : 'Sede Centro'}
          </h2>
          <p className="text-gray-500 mt-1">
            Revisa las estadísticas en tiempo real y el rendimiento general
          </p>
        </div>
        <div className="flex items-center gap-4 hidden md:flex">
          <div className="text-right">
            <span className="block text-sm font-semibold text-gray-800">{session.user.name}</span>
            <span className="block text-xs font-semibold text-[#f04b50]">{session.user.email}</span>
          </div>
          <div className="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center font-bold text-gray-400">
             AD
          </div>
        </div>
      </div>

      {/* 4 Cards de Métricas Principales */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <div className="bg-gradient-to-br from-green-500 to-green-600 p-6 rounded-xl text-white shadow-lg relative overflow-hidden">
             <div className="absolute top-0 right-0 -mt-4 -mr-4 w-24 h-24 bg-white opacity-10 rounded-full"></div>
             <p className="opacity-90 font-medium tracking-wide mb-1 text-sm uppercase">Pagos Aprobados</p>
             <h3 className="text-4xl font-extrabold">{pagosAprobados}</h3>
             <p className="text-xs font-medium mt-3 text-green-100 flex items-center gap-1">Inscritos formalmente en Sistema</p>
          </div>

          <div className="bg-gradient-to-br from-yellow-400 to-orange-400 p-6 rounded-xl text-white shadow-lg relative overflow-hidden">
             <div className="absolute top-0 right-0 -mt-4 -mr-4 w-24 h-24 bg-white opacity-10 rounded-full"></div>
             <p className="opacity-90 font-medium tracking-wide mb-1 text-sm uppercase">Reportes Pendientes</p>
             <h3 className="text-4xl font-extrabold">{pagosPendientes}</h3>
             <p className="text-xs font-medium mt-3 text-yellow-100 flex items-center gap-1">Requieren Verificación Manual</p>
          </div>

          <div className="bg-gradient-to-br from-red-500 to-red-600 p-6 rounded-xl text-white shadow-lg relative overflow-hidden">
             <div className="absolute top-0 right-0 -mt-4 -mr-4 w-24 h-24 bg-white opacity-10 rounded-full"></div>
             <p className="opacity-90 font-medium tracking-wide mb-1 text-sm uppercase">Pagos Rechazados</p>
             <h3 className="text-4xl font-extrabold">{pagosRechazados}</h3>
             <p className="text-xs font-medium mt-3 text-red-100 flex items-center gap-1">Transferencias Inválidas reportadas</p>
          </div>

          <div className="bg-gradient-to-br from-blue-600 to-indigo-600 p-6 rounded-xl text-white shadow-lg relative overflow-hidden">
             <div className="absolute top-0 right-0 -mt-4 -mr-4 w-24 h-24 bg-white opacity-10 rounded-full"></div>
             <p className="opacity-90 font-medium tracking-wide mb-1 text-sm uppercase">Carga Instructor</p>
             <h3 className="text-4xl font-extrabold">{totalHorasDadas} hrs</h3>
             <p className="text-xs font-medium mt-3 text-blue-100 flex items-center gap-1">Horas dictadas globales validadas</p>
          </div>
      </div>

       <div className="grid grid-cols-12 gap-6 mt-2">
         {/* Inscripciones Recientes */}
         <div className="col-span-12 lg:col-span-8 bg-white p-6 shadow-sm rounded-xl border border-gray-100">
           <div className="flex justify-between items-center mb-6">
              <h4 className="font-extrabold text-gray-800 text-lg">Inscripciones Recientes</h4>
              <button className="text-brand-500 font-semibold text-sm hover:underline">Ver Todas</button>
           </div>
           
           <table className="w-full text-left text-sm text-gray-500">
              <thead className="bg-gray-50 text-gray-700 uppercase font-semibold text-xs rounded-t-lg">
                 <tr>
                    <th scope="col" className="px-6 py-4 rounded-tl-lg">Estudiante</th>
                    <th scope="col" className="px-6 py-4">Curso Objetivo</th>
                    <th scope="col" className="px-6 py-4">Fecha Solicitud</th>
                    <th scope="col" className="px-6 py-4 rounded-tr-lg text-right">Estado Flujo</th>
                 </tr>
              </thead>
              <tbody>
                {inscripcionesRecientes.map((ins: any) => (
                  <tr key={ins.id} className="border-b border-gray-100 hover:bg-gray-50">
                    <td className="px-6 py-4">
                      <Link href={`/dashboard/usuarios?search=${ins.user?.telefono || ins.user?.email}`} className="block hover:text-blue-600 transition-colors">
                        <div className="font-extrabold text-gray-800 text-xs hover:underline">{((ins.user?.name || "") + " " + (ins.user?.apellido || "")).trim().toUpperCase()}</div>
                        <div className="text-gray-400 font-semibold text-[11px] mt-0.5 whitespace-nowrap">📞 {ins.user?.telefono || 'Sin tfno'}</div>
                      </Link>
                    </td>
                    <td className="px-6 py-4 font-semibold text-gray-800 text-xs">{ins.curso?.titulo}</td>
                    <td className="px-6 py-4 text-xs font-semibold text-gray-500">{new Date(ins.createdAt).toLocaleDateString()}</td>
                    <td className="px-6 py-4 text-right">
                       <span className={`px-3 py-1 rounded-full text-xs font-bold whitespace-nowrap ${
                         ins.estadoFlujo === "PENDIENTE_CONTACTAR" ? "bg-yellow-100 text-yellow-700" :
                         ins.estadoFlujo === "CONTACTADO" ? "bg-blue-100 text-blue-700" :
                         ins.estadoFlujo === "INSCRITO" ? "bg-green-100 text-green-700" :
                         "bg-gray-100 text-gray-700"
                       }`}>
                         {ins.estadoFlujo}
                       </span>
                    </td>
                  </tr>
                ))}
                {inscripcionesRecientes.length === 0 && (
                  <tr>
                    <td colSpan={4} className="text-center py-6 text-gray-400">No hay inscripciones recientes</td>
                  </tr>
                )}
              </tbody>
           </table>
         </div>

         {/* Totales de Cursos */}
         <div className="col-span-12 lg:col-span-4 bg-white p-6 shadow-sm rounded-xl border border-gray-100 flex flex-col items-center justify-center text-center">
            <h4 className="font-extrabold text-gray-800 mb-2">Cursos Disponibles Activos</h4>
            <div className="w-32 h-32 border-[14px] border-[#0066ff] border-t-transparent rounded-full flex items-center justify-center my-6 relative shadow-inner">
               <span className="text-3xl font-extrabold text-gray-800">{totalCursos}</span>
            </div>
            <p className="text-gray-400 text-sm px-4">Esta métrica engloba todo el pensum actualizado importado recientemente.</p>
         </div>
       </div>

    </div>
  );
}
