import { useState } from 'react';
import { Box, useMediaQuery } from '@mui/material';
import { useTheme } from '@mui/material/styles';
import AppHeader from './components/AppHeader';
import MenuDrawerPrivate, { OPEN_WIDTH, MINI_WIDTH } from './components/MenuDrawerPrivate';
import Footer from './components/Footer';
import Dashboard from './private/dashboard/Dashboard';
import UserManagement from './private/users/UserManagement';
import ProductCollections from './private/catalogs/products/ProductCollections';
import Categories from './private/catalogs/categories/Categories';
import LoginPage from './private/LoginPage';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useAuth } from './context/AuthContext';

const DRAWER_EXPANDED = OPEN_WIDTH;
const DRAWER_COLLAPSED = MINI_WIDTH;
const APPBAR_HEIGHT = 64;

export default function App() {
  const theme = useTheme();
  const isMobile = useMediaQuery('(max-width:900px)');
  const [drawerExpanded, setDrawerExpanded] = useState(true);
  const [currentView, setCurrentView] = useState('Dashboard');
  const { user, initializing } = useAuth();

  const mainLeft = isMobile ? 0 : (drawerExpanded ? DRAWER_EXPANDED : DRAWER_COLLAPSED);

  if (initializing) return null;

  if (!user) {
    return (
      <Routes>
        <Route path="/login" element={<LoginPage />} />
        <Route path="*" element={<Navigate to="/login" replace />} />
      </Routes>
    );
  }

  return (
    <>
      <AppHeader zone="private" currentPage={currentView} leftOffset={mainLeft} />

      <MenuDrawerPrivate
        onSelect={(value) => setCurrentView(value)}
        onExpandedChange={(expanded) => setDrawerExpanded(expanded)}
      />

      <Box
        component="main"
        sx={{
          ml: { xs: 0, md: `${mainLeft}px` },
          mt: `${APPBAR_HEIGHT}px`,
          p: 2,
          transition: theme.transitions.create('margin-left', {
            duration: theme.transitions.duration.standard,
            easing: theme.transitions.easing.sharp,
          }),
        }}
      >
        <Routes>
          <Route path="/login" element={<Navigate to="/" replace />} />
          <Route
            path="/"
            element={
              <>
                {currentView === 'Dashboard' && <Dashboard />}
                {currentView === '/Users/UserManagement' && <UserManagement />}
                {currentView === '/Products Management/Catalog Management/Product Collections' && (
                  <ProductCollections />
                )}
                {currentView === '/Products Management/Catalog Management/Categories' && (
                  <Categories />
                )}
              </>
            }
          />
        </Routes>
      </Box>

      <Box sx={{ height: 64 }} />
      <Footer zone="private" />
    </>
  );
}
