import React from 'react';
import { db } from "@/lib/db";
import { colegio, categoriamaster } from "@/db/schema";
import { eq } from "drizzle-orm";
import { getCursosWithColegio } from "@/lib/mariadb-relations";
import Link from 'next/link';
import { Monitor, Clock } from 'lucide-react';
import Navbar from '@/components/front/Navbar';
import Footer from '@/components/front/Footer';
import CursosFilterClient from './CursosFilterClient';

export default async function TodosLosCursosPage(
  props: { searchParams?: Promise<{ query?: string; categoria?: string; sede?: string }> }
) {
  const searchParams = await props.searchParams;
  const query     = searchParams?.query     || "";
  const categoria = searchParams?.categoria || "";
  const sedeId    = searchParams?.sede      || "";

  let nombreSede = "";
  if (sedeId) {
    const sede = await db.query.colegio.findFirst({
      where: eq(colegio.id, sedeId),
      columns: { nombre: true }
    });
    if (sede) nombreSede = sede.nombre;
  }

  // Categorías para el selector
  const categorias = await db.query.categoriamaster.findMany();
  categorias.sort((a, b) => a.nombre.localeCompare(b.nombre));

  const todosLosCursos = await getCursosWithColegio();

  // Filtros en memoria
  let cursos = todosLosCursos.filter(c => {
    if (sedeId && c.colegioId !== sedeId) return false;
    if (categoria && !c.categoria?.includes(categoria)) return false;
    if (query) {
      const q = query.toLowerCase();
      const enTitulo    = c.titulo?.toLowerCase().includes(q);
      const enCategoria = c.categoria?.toLowerCase().includes(q);
      const enColegio   = (c as any).colegio?.nombre?.toLowerCase().includes(q);
      if (!enTitulo && !enCategoria && !enColegio) return false;
    }
    return true;
  });
  cursos.sort((a, b) => a.titulo.localeCompare(b.titulo));

  return (
    <>
      <Navbar />
      <div className="min-h-screen bg-neutral-50 flex flex-col">
        {/* Hero Banner */}
        <div className="bg-gradient-to-tr from-[#3e2723] via-[#2b1910] to-[#1a0f0a] text-white py-24 px-8 text-center relative overflow-hidden">
          <div className="absolute inset-0 opacity-10 bg-cover bg-center" style={{ backgroundImage: "url('https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/Pila_de_libros.svg/512px-Pila_de_libros.svg.png')" }} />
          <div className="absolute top-0 right-0 w-64 h-64 bg-[#43a047] rounded-full blur-[100px] opacity-20 -mr-20 -mt-20"></div>
          <div className="absolute bottom-0 left-0 w-64 h-64 bg-[#f57c00] rounded-full blur-[100px] opacity-20 -ml-20 -mb-20"></div>
          
          <div className="relative z-10 max-w-2xl mx-auto">
            <h1 className="text-4xl md:text-5xl font-extrabold mb-4 tracking-tight drop-shadow-md">Cursos Disponibles</h1>
            <div className="flex justify-center items-center gap-2 text-sm text-[#fbc02d] font-semibold mt-3">
              <Link href="/" className="hover:text-white transition-colors">Inicio</Link>
              <span className="text-gray-400">/ Inicia / Certifícate</span>
            </div>
          </div>
        </div>

        <div className="max-w-7xl mx-auto px-6 py-12 w-full flex-grow relative z-20 -mt-8">
          <div className="bg-white rounded-2xl shadow-xl p-2 mb-8 border border-green-50">
            <CursosFilterClient
              categorias={categorias.map(c => ({ id: c.id, nombre: c.nombre, icono: c.icono }))}
              currentQuery={query}
              currentCategoria={categoria}
            />
          </div>

          {sedeId && nombreSede && (
            <div className="bg-gradient-to-r from-[#e8f5e9] to-[#c8e6c9] text-[#2e7d32] p-6 rounded-2xl mb-8 flex flex-col sm:flex-row justify-between items-center shadow-sm border border-[#a5d6a7]">
              <div className="mb-4 sm:mb-0">
                <div className="font-extrabold text-xl flex items-center gap-2">🏫 Sede: {nombreSede}</div>
                <p className="text-sm font-medium opacity-90">Mostrando exclusivamente la oferta académica de esta institución.</p>
              </div>
              <Link href="/cursos" className="bg-white text-[#2e7d32] px-6 py-3 rounded-xl font-bold shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all whitespace-nowrap">
                Ver todos los cursos
              </Link>
            </div>
          )}

          <div className="text-sm font-medium text-gray-500 mb-8 ml-2">
            {cursos.length === 0
              ? "No se encontraron cursos."
              : `${cursos.length} curso${cursos.length > 1 ? 's' : ''} encontrado${cursos.length > 1 ? 's' : ''}${query ? ` para "${query}"` : ''}${categoria ? ` en ${categoria}` : ''}`
            }
          </div>

          {cursos.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
              {cursos.map((cursoItem, idx) => (
                <Link href={`/cursos/${cursoItem.id}`} key={cursoItem.id}
                  className="group bg-white rounded-2xl shadow-md border border-gray-100 overflow-hidden flex flex-col hover:shadow-2xl transition-all duration-300 transform hover:-translate-y-2">
                  <div className={`h-48 flex items-center justify-center bg-gradient-to-br ${
                    idx % 4 === 0 ? 'from-[#e8f5e9] to-[#c8e6c9]' :
                    idx % 4 === 1 ? 'from-[#fff3e0] to-[#ffe0b2]' :
                    idx % 4 === 2 ? 'from-[#fffde7] to-[#fff9c4]' :
                    'from-[#efebe9] to-[#d7ccc8]'
                  } relative overflow-hidden`}>
                    <span className="text-6xl opacity-40 group-hover:scale-125 group-hover:rotate-6 transition-all duration-500">
                      {categorias.find(c => c.nombre === cursoItem.categoria)?.icono || '📚'}
                    </span>
                    <div className="absolute top-4 left-4">
                      <span className="bg-[#f57c00] text-white text-[10px] font-bold uppercase tracking-wider py-1.5 px-3 rounded-full shadow-md">
                        {cursoItem.categoria}
                      </span>
                    </div>
                  </div>

                  <div className="p-6 flex-grow flex flex-col justify-between">
                    <div>
                      <div className="flex items-center gap-4 text-xs font-medium text-gray-500 mb-3">
                        <span className="flex items-center gap-1"><Monitor className="w-3.5 h-3.5 text-[#43a047]" /> Online/Pres.</span>
                        <span className="flex items-center gap-1"><Clock className="w-3.5 h-3.5 text-[#f57c00]" /> {new Date(cursoItem.fechaInicio).toLocaleDateString('es-VE', { day: '2-digit', month: 'short' })}</span>
                      </div>
                      <h4 className="text-lg font-extrabold text-[#3e2723] leading-snug group-hover:text-[#f57c00] transition-colors line-clamp-2 mb-2">
                        {cursoItem.titulo}
                      </h4>
                      <p className="text-xs font-semibold text-[#43a047] bg-[#e8f5e9] inline-block px-2 py-1 rounded-md">🏫 {(cursoItem as any).colegio?.nombre}</p>
                    </div>

                    <div className="flex items-center justify-between mt-5 pt-5 border-t border-gray-100">
                      <span className="text-xs text-gray-400 font-semibold bg-gray-50 px-2 py-1 rounded-md border border-gray-200">
                        {cursoItem.matriculaMax ? `${cursoItem.inscritosCount ?? 0}/${cursoItem.matriculaMax} cupos` : 'Cupos disponibles'}
                      </span>
                      <div className="text-right">
                        <div className="text-xl font-black text-[#2b1910]">${Number(cursoItem.precio).toFixed(2)} <span className="text-xs font-semibold text-gray-500">total</span></div>
                        {cursoItem.duracionSemanas ? (
                          <div className="text-[10px] uppercase font-bold text-[#f57c00] mt-0.5">${(Number(cursoItem.precio) / cursoItem.duracionSemanas).toFixed(2)} / sem ({cursoItem.duracionSemanas} sem)</div>
                        ) : null}
                      </div>
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          ) : (
            <div className="text-center py-24 bg-white rounded-2xl shadow-sm border border-gray-100">
              <div className="text-6xl mb-6">🌱</div>
              <h3 className="text-2xl font-bold text-[#3e2723] mb-3">Sin resultados por ahora</h3>
              <p className="text-gray-500 max-w-md mx-auto">Sigue explorando nuestro catálogo, pronto abriremos nuevos cursos en esta área.</p>
              <Link href="/cursos" className="mt-8 inline-block bg-[#f57c00] text-white px-8 py-3.5 rounded-xl font-bold hover:bg-[#e65100] hover:-translate-y-1 transition-all duration-300 shadow-lg shadow-[#f57c00]/30">
                Ver todos los cursos
              </Link>
            </div>
          )}
        </div>
      </div>
      <Footer />
    </>
  );
}
