'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 AlumnosPage() {
  const { user, loading } = useAuth();
  const router = useRouter();
  const [alumnos, setAlumnos] = useState<any[]>([]);
  const [busqueda, setBusqueda] = useState('');
  const [loadingData, setLoadingData] = useState(true);

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

  const handleSearch = async () => {
    setLoadingData(true);
    try {
      const data = await api.get('/alumno', { tipoBusqueda: 'NOMBRE', nombre: busqueda });
      setAlumnos(Array.isArray(data) ? data : []);
    } catch { /* ignore */ }
    setLoadingData(false);
  };

  if (loading) return <LoadingSpinner />;

  return (
    <div>
      <h3 className="mb-3">Alumnos</h3>
      <div className="input-group mb-3">
        <input className="form-control" value={busqueda} onChange={e => setBusqueda(e.target.value)}
          placeholder="Buscar alumno..." onKeyDown={e => e.key === 'Enter' && handleSearch()} />
        <button className="btn btn-primary" onClick={handleSearch}>Buscar</button>
      </div>
      <div className="card shadow">
        <div className="card-body">
          <table className="table table-hover">
            <thead>
              <tr><th>RUT</th><th>Nombre</th><th>Mail</th><th>Teléfono</th></tr>
            </thead>
            <tbody>
              {alumnos.map((a: any, i: number) => (
                <tr key={i}>
                  <td>{a.AlumnoRut || a.rut || a.Rut}</td>
                  <td>{a.NombreAlumno || a.nombre || a.Nombre}</td>
                  <td>{a.Email || a.mail || a.Mail}</td>
                  <td>{a.Telefono || a.telefono || a.Fono}</td>
                </tr>
              ))}
              {alumnos.length === 0 && <tr><td colSpan={4} className="text-center">Sin resultados</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
