import { SideNav } from '@rkheftan/harmony-ui';
import { buildNavItems } from './buildNavItems';
import { appRoutes } from '@/routes/config';
import { Outlet, useLocation } from 'react-router-dom';
import { Box, useMediaQuery, useTheme } from '@mui/material';
import { Header } from './Header';
import { Suspense, useState } from 'react';
import { Toolbar } from './Toolbar';
import { useAuth } from '@/hooks/useAuth';
import { Loading } from '../routes/Loading';

export const Layout = () => {
  const navItemConfigs = buildNavItems(appRoutes);
  const location = useLocation();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const [sideNavOpen, setSideNavOpen] = useState(false);
  const { userInfo } = useAuth();

  return (
    <Box
      sx={{
        height: '100vh',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <Box
        sx={{
          // TODO: Check for better approach
          width: isMobile ? '100%' : 1070,
          height: isMobile ? '100vh' : '80%',
          display: 'flex',
          flexDirection: 'row-reverse',
          borderRadius: isMobile ? 0 : 4,
          backgroundColor: 'background.paper',
          overflow: 'hidden',
        }}
      >
        <Box sx={{ flex: 1 }}>
          <Toolbar
            isMobile={isMobile}
            sideNavOpen={sideNavOpen}
            setSideNavOpen={setSideNavOpen}
            user={userInfo}
          />
          <Box
            sx={{
              flex: 1,
              overflowY: 'auto',
              p: 2,
              maxHeight: 'calc(100% - 85px)',
              overflowInline: 'auto',
            }}
          >
            <Suspense fallback={<Loading />}>
              <Outlet />
            </Suspense>
          </Box>
        </Box>

        <SideNav
          open={sideNavOpen}
          onClose={() => setSideNavOpen(false)}
          header={isMobile ? undefined : <Header user={userInfo} />}
          footer={isMobile ? <Header user={userInfo} /> : undefined}
          navConfig={navItemConfigs}
          activePath={location.pathname + location.hash}
          selectedVariant="textOnly"
          positioning="absolute"
          sideNavVariant={isMobile ? 'temporary' : 'full'}
          top={8.125}
        />
      </Box>
    </Box>
  );
};
