import React, { useState, useEffect } from "react";
import { styled, ThemeProvider, createTheme } from "@mui/material/styles";
import Box from "@mui/material/Box";
import CssBaseline from "@mui/material/CssBaseline";
import TopBar from "./components/TopBar";
import Sidebar from "./components/Sidebar";
import { getDesignTokens } from "./theme";
import { Outlet, useLocation } from "react-router-dom";
import ScrollToTop from "./components/ScrollToTop";
import useMediaQuery from "@mui/material/useMediaQuery";

const DrawerHeader = styled("div")(({ theme }) => ({
    display: "flex",
    alignItems: "center",
    justifyContent: "flex-end",
    padding: theme.spacing(0, 1),
    ...theme.mixins.toolbar,
}));

const DashboardLayout = ({ role }) => {
    const [mode, setMode] = useState(
        localStorage.getItem("currentMode") || "light"
    );

    const theme = React.useMemo(
        () => createTheme(getDesignTokens(mode, role)),
        [mode, role]
    );

    const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
    const [open, setOpen] = useState(!isMobile);
    const location = useLocation();

    useEffect(() => {
        setOpen(!isMobile);
    }, [isMobile]);

    const handleDrawerOpen = () => {
        setOpen(true);
    };

    const handleDrawerClose = () => {
        setOpen(false);
    };

    const handleDrawerToggle = () => {
        setOpen((previousOpen) => !previousOpen);
    };

    return (
        <ThemeProvider theme={theme}>
            <Box sx={{ display: "flex", minHeight: "100vh" }}>
                <div id="back-to-top-anchor" />

                <CssBaseline />

                <TopBar
                    open={open}
                    handleDrawerToggle={handleDrawerToggle}
                    setMode={setMode}
                    role={role}
                    isMobile={isMobile}
                />

                <Sidebar
                    open={open}
                    handleDrawerClose={handleDrawerClose}
                    role={role}
                    pathname={location.pathname}
                    variant={isMobile ? "temporary" : "permanent"}
                />

                <Box
                    component="main"
                    sx={{
                        flexGrow: 1,
                        minWidth: 0,
                        width: "100%",
                        p: 3,
                    }}
                >
                    <DrawerHeader />
                    <Outlet />
                </Box>

                <ScrollToTop />
            </Box>
        </ThemeProvider>
    );
};

export default DashboardLayout;