import {
    Box,
    IconButton,
    Stack,
    Toolbar,
    useTheme,
    Menu,
    MenuItem,
} from "@mui/material";

import MuiAppBar from "@mui/material/AppBar";
import MenuIcon from "@mui/icons-material/Menu";
import Person2OutlinedIcon from "@mui/icons-material/Person2Outlined";
import LightModeOutlinedIcon from "@mui/icons-material/LightModeOutlined";
import DarkModeOutlinedIcon from "@mui/icons-material/DarkModeOutlined";
import LogoutIcon from "@mui/icons-material/Logout";

import { styled } from "@mui/material/styles";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { logout } from "../utils/auth";

const drawerWidth = 240;

const AppBar = styled(MuiAppBar, {
    shouldForwardProp: (prop) => prop !== "open",
})(({ theme, open }) => ({
    zIndex: theme.zIndex.drawer + 1,
    color: "white",

    transition: theme.transitions.create(["width", "margin"], {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.leavingScreen,
    }),

    ...(open && {
        marginLeft: drawerWidth,
        width: `calc(100% - ${drawerWidth}px)`,

        transition: theme.transitions.create(["width", "margin"], {
            easing: theme.transitions.easing.sharp,
            duration: theme.transitions.duration.enteringScreen,
        }),
    }),
}));

const TopBar = ({
    open,
    handleDrawerToggle,
    setMode,
}) => {
    const theme = useTheme();
    const navigate = useNavigate();

    const [anchorEl, setAnchorEl] = useState(null);
    const openUserMenu = Boolean(anchorEl);

    const handleMenuOpen = (event) => {
        setAnchorEl(event.currentTarget);
    };

    const handleMenuClose = () => {
        setAnchorEl(null);
    };

    const handleLogout = async () => {
        const success = await logout();

        if (success) {
            handleMenuClose();
            navigate("/login");
        } else {
            console.error("Logout failed");
        }
    };

    const toggleTheme = () => {
        const nextMode =
            theme.palette.mode === "light" ? "dark" : "light";

        localStorage.setItem("currentMode", nextMode);
        setMode(nextMode);
    };

    return (
        <AppBar
            position="fixed"
            component="header"
            open={open}
        >
            <Toolbar>
                <IconButton
                    color="inherit"
                    aria-label={open ? "Close sidebar" : "Open sidebar"}
                    onClick={handleDrawerToggle}
                    edge="start"
                    sx={{
                        marginRight: 5,
                        display: "flex",
                    }}
                >
                    <MenuIcon />
                </IconButton>

                <Box sx={{ flexGrow: 1 }} />

                <Stack direction="row">
                    <IconButton
                        onClick={toggleTheme}
                        color="inherit"
                        aria-label="Toggle theme"
                    >
                        {theme.palette.mode === "light" ? (
                            <LightModeOutlinedIcon />
                        ) : (
                            <DarkModeOutlinedIcon />
                        )}
                    </IconButton>

                    <IconButton
                        id="user-button"
                        color="inherit"
                        onClick={handleMenuOpen}
                        aria-controls={
                            openUserMenu ? "user-menu" : undefined
                        }
                        aria-haspopup="true"
                        aria-expanded={
                            openUserMenu ? "true" : undefined
                        }
                    >
                        <Person2OutlinedIcon />
                    </IconButton>

                    <Menu
                        id="user-menu"
                        anchorEl={anchorEl}
                        open={openUserMenu}
                        onClose={handleMenuClose}
                        MenuListProps={{
                            "aria-labelledby": "user-button",
                        }}
                    >
                        <MenuItem onClick={handleLogout}>
                            <LogoutIcon sx={{ mr: 1 }} />
                            Logout
                        </MenuItem>
                    </Menu>
                </Stack>
            </Toolbar>
        </AppBar>
    );
};

export default TopBar;