'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 EmpresasPage() {
  const { user, loading } = useAuth();
  const router = useRouter();
  const [empresas, setEmpresas] = useState<any[]>([]);
  const [loadingData, setLoadingData] = useState(true);

  useEffect(() => {
    if (!loading && !user) router.push('/login');
    if (user) {
      api.get('/empresa', { busqueda: 'LISTADO', rut: '', varB: '', varC: 0 }).then(data => {
        setEmpresas(Array.isArray(data) ? data : []);
        setLoadingData(false);
      }).catch(() => setLoadingData(false));
    }
  }, [user, loading, router]);

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

  return (
    <div>
      <h3 className="mb-3">Empresas</h3>
      <div className="card shadow">
        <div className="card-body">
          <table className="table table-hover">
            <thead>
              <tr><th>RUT</th><th>Razón Social</th><th>Contacto</th><th>Mail</th></tr>
            </thead>
            <tbody>
              {empresas.map((e: any, i: number) => (
                <tr key={i} style={{ cursor: 'pointer' }} onClick={() => router.push(`/empresas/${e.Rut || e.rut}`)}>
                  <td>{e.Rut || e.rut}</td>
                  <td>{e.RazonSocial || e.razonSocial || e.Nombre}</td>
                  <td>{e.Contacto || e.contacto}</td>
                  <td>{e.Mail || e.mail}</td>
                </tr>
              ))}
              {empresas.length === 0 && <tr><td colSpan={4} className="text-center">Sin empresas</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
