import React, { lazy, Suspense } from 'react';
import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { RhLayout } from './components/layout/RhLayout';
import { useAuthContext } from '@/components/shared/AuthProvider';
import { LoadingOverlay } from '@/components/shared/LoadingOverlay';

const PageLoader = () => (
  <LoadingOverlay isLoading={true} message="Carregando RH..." fullScreen variant="premium" />
);

const RhProtectedRoute = ({ children }) => {
  const { user, loading, isAuthorized } = useAuthContext();
  const location = useLocation();

  if (loading) return <PageLoader />;
  if (!user || !isAuthorized('rh')) {
    return <Navigate to="/plataforma/rh/login" state={{ from: location }} replace />;
  }

  return children;
};

// Lazy Load Views
const RhLoginView = lazy(() => import('./views/RhLoginView').then(m => ({ default: m.RhLoginView })));
const RhDashboardView = lazy(() => import('./views/RhDashboardView').then(m => ({ default: m.RhDashboardView })));
const EmployeesView = lazy(() => import('./views/EmployeesView').then(m => ({ default: m.EmployeesView })));
const PontoPage = lazy(() => import('./ponto-eletronico/components/PontoPage').then(m => ({ default: m.PontoPage })));

/**
 * Rotas do módulo de RH.
 * Implementa isolamento e estrutura de layout específica.
 */
export const RhRoutes = () => {
    return (
        <Suspense fallback={<PageLoader />}>
            <Routes>
                {/* Rota de Login do RH */}
                <Route path="login" element={<RhLoginView />} />
                
                {/* Rotas protegidas pelo Layout do RH */}
                <Route element={
                    <RhProtectedRoute>
                        <RhLayout />
                    </RhProtectedRoute>
                }>
                    <Route path="dashboard" element={<RhDashboardView />} />
                    <Route path="colaboradores" element={<EmployeesView />} />
                    <Route path="ponto" element={<PontoPage />} />
                    
                    {/* Redirecionamentos de conveniência */}
                    <Route index element={<Navigate to="dashboard" replace />} />
                </Route>

                <Route path="*" element={<Navigate to="/plataforma/rh/login" replace />} />
            </Routes>
        </Suspense>
    );
};
