import { mensajecontacto } from "@/db/schema";
import { eq } from "drizzle-orm";
import { Mail } from "lucide-react";
import MensajesClient from "./MensajesClient";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { getMensajesWithColegio } from "@/lib/mariadb-relations";

export const dynamic = "force-dynamic";

export default async function NotificacionesPage() {
  const session = await getServerSession(authOptions);
  const role = session?.user?.role;
  const colegioId = session?.user?.colegioId;

  let mensajes: Awaited<ReturnType<typeof getMensajesWithColegio>> = [];
  try {
    mensajes = await getMensajesWithColegio(
      role === "ADMIN_COLEGIO" && colegioId
        ? eq(mensajecontacto.colegioId, colegioId)
        : undefined
    );
    mensajes.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
  } catch {
    // Error al cargar mensajes
  }

  const noLeidos = mensajes.filter((m) => !m.leido).length;

  return (
    <div className="p-8 max-w-5xl mx-auto">
      <div className="flex justify-between items-center mb-8">
        <div>
          <h1 className="text-3xl font-extrabold text-gray-800">Bandeja de Mensajes</h1>
          <p className="text-gray-500">
            Consultas recibidas desde el formulario de contacto del sitio web.
          </p>
        </div>
        {noLeidos > 0 && (
          <span className="bg-[#f04b50] text-white font-bold px-4 py-2 rounded-full text-sm">
            {noLeidos} sin leer
          </span>
        )}
      </div>

      {mensajes.length === 0 ? (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-16 text-center">
          <Mail className="w-16 h-16 text-gray-200 mx-auto mb-4" />
          <h3 className="text-xl font-bold text-gray-500 mb-2">Bandeja vacía</h3>
          <p className="text-gray-400 text-sm">
            Cuando alguien envíe un mensaje desde el formulario de contacto aparecerá aquí.
          </p>
        </div>
      ) : (
        <MensajesClient mensajes={mensajes} />
      )}
    </div>
  );
}
