import { lazy, Suspense } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { PortalHome } from '@/features/portal';
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 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 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').then(m => ({ default: m.WorkspaceLayout })));

// 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();

  if (loading) return <PageLoader />;
  if (!user || !isAuthorized(environment)) return <Navigate to={loginPath} replace />;

  return children;
};

function App() {
  return (
    <AuthProvider>
      <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 />} />
          {/* 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 (Legacy) */}
          <Route path="/plataforma/hr">
            <Route path="login" element={<HRLogin />} />
            <Route path="dashboard" element={
              <ProtectedRoute loginPath="/plataforma/hr/login" environment="hr">
                <HRDashboard />
              </ProtectedRoute>
            } />
            <Route path="ponto" element={
              <ProtectedRoute loginPath="/plataforma/hr/login" environment="hr">
                <PontoPage />
              </ProtectedRoute>
            } />
            <Route index element={<Navigate to="/plataforma/hr/login" replace />} />
          </Route>
        {/* 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>

        {/* Workspace Environment - Novo Ambiente Modernizado */}
        <Route path="/plataforma/workspace/*" element={
          <ProtectedRoute loginPath="/plataforma/auth/login" environment="financeiro">
            <WorkspaceLayout />
          </ProtectedRoute>
        } />

        {/* Fallback */}
          <Route path="*" element={<Navigate to="/plataforma/" replace />} />
        </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;
