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

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

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

  return (
    <div>
      <h3 className="mb-3">Ventas Empresas</h3>
      <div className="card shadow">
        <div className="card-body">
          <table className="table table-hover">
            <thead>
              <tr><th>Empresa</th><th>Curso</th><th>Valor</th><th>Fecha</th></tr>
            </thead>
            <tbody>
              {ventas.map((v: any, i: number) => (
                <tr key={i}>
                  <td>{v.Empresa || v.empresa}</td>
                  <td>{v.Curso || v.curso}</td>
                  <td>${(v.Valor || v.valor || 0).toLocaleString()}</td>
                  <td>{v.Fecha ? new Date(v.Fecha).toLocaleDateString() : ''}</td>
                </tr>
              ))}
              {ventas.length === 0 && <tr><td colSpan={4} className="text-center">Sin ventas</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
