'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/hooks/useAuth';
import { api } from '@/services/api';
import LoadingSpinner from '@/components/LoadingSpinner';

export default function CursosPage() {
  const { user, loading } = useAuth();
  const router = useRouter();
  const [cursos, setCursos] = useState<any[]>([]);
  const [loadingData, setLoadingData] = useState(true);

  useEffect(() => {
    if (!loading && !user) router.push('/login');
    if (user) {
      api.get('/curso', { tipoBusqueda: 'NOMBRE', nombre: '' }).then(data => {
        setCursos(Array.isArray(data) ? data : []);
        setLoadingData(false);
      }).catch(() => setLoadingData(false));
    }
  }, [user, loading, router]);

  if (loading || loadingData) return <LoadingSpinner />;

  return (
    <div>
      <h3 className="mb-3">Cursos</h3>
      <div className="card shadow">
        <div className="card-body">
          <table className="table table-hover">
            <thead>
              <tr><th>ID</th><th>Nombre</th><th>Programa</th><th>Duración</th></tr>
            </thead>
            <tbody>
              {cursos.map((c: any, i: number) => (
                <tr key={i}>
                  <td>{c.idCursos || c.Id || i}</td>
                  <td>{c.Curso || c.Nombre || c.nombre}</td>
                  <td>{c.Programa || c.programa}</td>
                  <td>{c.Duracion || c.duracion || '-'}</td>
                </tr>
              ))}
              {cursos.length === 0 && <tr><td colSpan={4} className="text-center">Sin cursos</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
