import { lazy, Suspense } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { Toaster } from 'sonner';
import { PortalHome } from './features/portal/components/PortalHome.jsx';
import AuthProvider, { useAuthContext } from '@/components/shared/AuthProvider';

import { Building, Zap } from 'lucide-react';
import { LoadingOverlay } from '@/components/shared/LoadingOverlay';
import { useGlobalLoading } from '@/hooks/useGlobalLoading';

// Lazy loading feature components
const FleetLogin = lazy(() => import('@/features/fleet').then(m => ({ default: m.FleetLogin })));
const FleetDashboard = lazy(() => import('@/features/fleet').then(m => ({ default: m.FleetDashboard })));
const HRLogin = lazy(() => import('@/features/rh').then(m => ({ default: m.HRLogin })));
const HRDashboard = lazy(() => import('@/features/rh').then(m => ({ default: m.HRDashboard })));
const PontoPage = lazy(() => import('@/features/rh').then(m => ({ default: m.PontoPage })));
const RhRoutes = lazy(() => import('@/features/rh/routes').then(m => ({ default: m.RhRoutes })));
const LoginPage = lazy(() => import('@/features/auth/login/LoginPage').then(m => ({ default: m.LoginPage })));
const FinanceLogin = lazy(() => import('@/features/auth/login-finance/LoginPage').then(m => ({ default: m.LoginPage })));
const CnabLogin = lazy(() => import('@/features/auth/login-cnab/LoginPage').then(m => ({ default: m.LoginPage })));
const FleetV2App = lazy(() => import('@/features/fleet-v2').then(m => ({ default: m.FleetV2App })));
const FinanceiroV2App = lazy(() => import('@/features/financeiro-v2').then(m => ({ default: m.FinanceiroV2App })));
const PrafrotRoutes = lazy(() => import('@/features/prafrot/routes').then(m => ({ default: m.PrafrotRoutes })));
const PrafrotLogin = lazy(() => import('@/features/prafrot/views/LoginView'));
const TableDebug = lazy(() => import('@/features/prafrot/views/TableDebug'));
const PlaygroundView = lazy(() => import('@/features/dev-tools/views/PlaygroundView'));
const WorkspaceLayout = lazy(() => import('@/features/workspace/components/WorkspaceLayout.jsx').then(m => ({ default: m.WorkspaceLayout })));
const LoginView = lazy(() => import('@/features/workspace/views/LoginView.jsx').then(m => ({ default: m.LoginView })));
const WorkspaceGuard = lazy(() => import('@/features/workspace/components/WorkspaceGuard.jsx').then(m => ({ default: m.WorkspaceGuard })));
const CnabRoutes = lazy(() => import('@/features/financeiro-cnab/routes').then(m => ({ default: m.CnabRoutes })));
const GrRoutes = lazy(() => import('@/features/gr/routes').then(m => ({ default: m.GrRoutes })));
const GrLogin = lazy(() => import('@/features/gr/views/LoginView'));
const GrResetPassword = lazy(() => import('@/features/gr/views/ResetPasswordView'));
const ExternalDriverRegistration = lazy(() => import('@/features/gr/views/ExternalDriverRegistrationView').then(m => ({ default: m.ExternalDriverRegistrationView })));
const DriverPortalView = lazy(() => import('@/features/prafrot/views/DriverPortalView').then(m => ({ default: m.DriverPortalView })));
const AutoLabRoutes = lazy(() => import('@/features/autolab/routes').then(m => ({ default: m.AutoLabRoutes })));
const AutoLabLogin = lazy(() => import('@/features/autolab/views/AutoLabLoginView'));
const OestPanRoutes = lazy(() => import('@/features/Oest_Pan/routes').then(m => ({ default: m.OestPanRoutes })));
const OestPanLogin = lazy(() => import('@/features/Oest_Pan/views/LoginView'));


// Loading component
const PageLoader = () => (
  <LoadingOverlay isLoading={true} message="Carregando Aplicação..." fullScreen variant="premium" />
);

/**
 * Componente de proteção de rotas.
 * Redireciona para o login se o usuário não estiver autenticado.
 */


const ProtectedRoute = ({ children, loginPath = '/plataforma/auth/login', environment = 'global' }) => {
  const { user, loading, isAuthorized } = useAuthContext();
  const location = useLocation();

  if (loading) return <PageLoader />;
  
  // Verifica autorização - isAuthorized já verifica o usuário do módulo específico
  if (!isAuthorized(environment)) {
    return <Navigate to={loginPath} state={{ from: location }} replace />;
  }

  return children;
};

function App() {
  return (
    <AuthProvider>
      <Toaster position="top-right" richColors closeButton />
      <LoadingOverlayWrapper />
      <Router>
        <Suspense fallback={<PageLoader />}>
          <Routes>
          {/* Portal Home - System Selection */}
          <Route path="/plataforma/" element={<PortalHome />} />
          
          {/* 🔧 COMPONENT LABORATORY - Design System Testing */}
          <Route path="/plataforma/debug/playground" element={
            <Suspense fallback={<PageLoader />}>
              <PlaygroundView />
            </Suspense>
          } />
          
          {/* Auth Login - Explícitos */}
          <Route path="/plataforma/auth/login" element={<LoginPage />} />
          <Route path="/plataforma/auth/login-finance" element={<FinanceLogin />} />
          <Route path="/plataforma/auth/login-cnab" element={<CnabLogin />} />
          {/* Fleet Management Management (Legacy) */}
          <Route path="/plataforma/fleet">
            <Route path="login" element={<FleetLogin />} />
            <Route path="dashboard" element={
              <ProtectedRoute loginPath="/plataforma/fleet/login" environment="fleet">
                <FleetDashboard />
              </ProtectedRoute>
            } />
            <Route index element={<Navigate to="/plataforma/fleet/login" replace />} />
          </Route>
          {/* HR Management (Modern) */}
          <Route path="/plataforma/rh/*" element={<RhRoutes />} />
        {/* Fleet V2 Environment - Protegido */}
        <Route path="/plataforma/fleet-v2/*" element={
          <ProtectedRoute loginPath="/plataforma/auth/login" environment="fleet">
            <FleetV2App />
          </ProtectedRoute>
        } />

        {/* Financeiro V2 Environment - Protegido */}
        <Route path="/plataforma/financeiro-v2/*" element={
          <ProtectedRoute loginPath="/plataforma/auth/login-finance" environment="financeiro">
            <FinanceiroV2App />
          </ProtectedRoute>
        } />

        {/* Prafrot Environment */}
        <Route path="/plataforma/prafrot">
          <Route path="login" element={<PrafrotLogin />} />
          <Route path="*" element={
            <ProtectedRoute loginPath="/plataforma/prafrot/login" environment="prafrot">
              <PrafrotRoutes />
            </ProtectedRoute>
          } />
          <Route index element={<Navigate to="/plataforma/prafrot/login" replace />} />
        </Route>

        <Route path="/plataforma/solicitacao-viagem" element={
            <Suspense fallback={<PageLoader />}>
              <DriverPortalView />
            </Suspense>
        } />

        {/* GR Environment (Gestão de Risco) */}
        <Route path="/plataforma/gr">
          <Route path="login" element={<GrLogin />} />
          <Route path="reset-senha" element={<GrResetPassword />} />
          <Route path="*" element={
            <ProtectedRoute loginPath="/plataforma/gr/login" environment="gr">
              <GrRoutes />
            </ProtectedRoute>
          } />
          <Route index element={<Navigate to="/plataforma/gr/login" replace />} />
        </Route>

        {/* Workspace Environment - Novo Ambiente Modernizado */}
        <Route path="/plataforma/workspace/login" element={<LoginView />} />
        <Route path="/plataforma/workspace" element={
          <WorkspaceGuard>
            <WorkspaceLayout />
          </WorkspaceGuard>
        } />
        <Route path="/plataforma/workspace/*" element={
          <WorkspaceGuard>
            <WorkspaceLayout />
          </WorkspaceGuard>
        } />

        {/* Financeiro CNAB Environment */}
        <Route path="/plataforma/financeiro-cnab/*" element={
          <ProtectedRoute loginPath="/plataforma/auth/login-cnab" environment="financeiro">
            <CnabRoutes />
          </ProtectedRoute>
        } />

        {/* Auto Lab Environment */}
        <Route path="/plataforma/autolab">
          <Route path="login" element={<AutoLabLogin />} />
          <Route path="*" element={
            <ProtectedRoute loginPath="/plataforma/autolab/login" environment="autolab">
              <AutoLabRoutes />
            </ProtectedRoute>
          } />
        <Route index element={<Navigate to="/plataforma/autolab/login" replace />} />
        </Route>

        {/* Oeste Pan Environment */}
        <Route path="/plataforma/oest-pan">
          <Route path="login" element={<OestPanLogin />} />
          <Route path="*" element={
            <ProtectedRoute loginPath="/plataforma/oest-pan/login" environment="auth_oestepan">
              <OestPanRoutes />
            </ProtectedRoute>
          } />
          <Route index element={<Navigate to="/plataforma/oest-pan/login" replace />} />
        </Route>


        {/* Fallback */}
          <Route path="*" element={<Navigate to="/plataforma/" replace />} />

        {/* GR Public Routes */}
        <Route path="/plataforma/cadastro-motorista" element={
            <Suspense fallback={<PageLoader />}>
              <ExternalDriverRegistration />
            </Suspense>
        } />
        </Routes>
      </Suspense>
    </Router>
  </AuthProvider>
);
}

// Wrapper component to use the hook inside the provider context if needed, 
// though here it's at the top level so we just need to import the store.
const LoadingOverlayWrapper = () => {
  const { isLoading, loadingMessage } = useGlobalLoading();
  return <LoadingOverlay isLoading={isLoading} message={loadingMessage} fullScreen />;
};

export default App;
