import * as React from "react";
import { styled, useTheme, Theme, CSSObject } from "@mui/material/styles";
import MuiDrawer from "@mui/material/Drawer";
import MuiAppBar, { AppBarProps as MuiAppBarProps } from "@mui/material/AppBar";
import Toolbar from "@mui/material/Toolbar";
import List from "@mui/material/List";
import CssBaseline from "@mui/material/CssBaseline";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import MenuIcon from "@mui/icons-material/Menu";
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
import Divider from "@mui/material/Divider";
import ListItem from "@mui/material/ListItem";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import InboxIcon from "@mui/icons-material/MoveToInbox";
import MailIcon from "@mui/icons-material/Mail";
import Box from "@mui/material/Box";
import { useStyles } from "../../theme/appStyles";
import {
  Avatar,
  Grid,
  InputAdornment,
  TextField,
  useMediaQuery,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import UserImg from "../../Images/user_login_photo.webp";
import { useState, useEffect } from "react";
import { useThemeContext } from "./ThemeContext";
import Notification from "../../Components/Popup/notification";

import { MdOutlineNotificationsNone } from "react-icons/md";
import { MdDarkMode } from "react-icons/md";
import { CiSearch } from "react-icons/ci";
import Profile from "../../Components/Popup/profile";
import { appColors } from "../../theme/appcolors";






const drawerWidth = 280;
const headerHeight = 100;
interface AppBarProps extends MuiAppBarProps {
  open?: boolean;
}

const AppBar = styled(MuiAppBar, {
  shouldForwardProp: (prop) => prop !== "open",
})<AppBarProps>(({ theme, open }) => ({
  zIndex: theme.zIndex.drawer + 1,
  height: headerHeight,
  transition: theme.transitions.create(["width", "margin"], {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  ...(open && {
    marginLeft: drawerWidth,
    width: `calc(100% - ${drawerWidth}px)`,
    paddingLeft: 0,
    
  }),
  ...(!open && {
    marginLeft: 0,
    width: "100%",
    paddingLeft: "75px",
    [theme.breakpoints.down("md")]: {
      paddingLeft: "0px",
    },
  }),
}));

const IsNotMobileDrawer = styled(MuiDrawer, {
  shouldForwardProp: (prop) => prop !== "open",
})(({ theme, open }) => ({
  width: drawerWidth,
  flexShrink: 0,
  whiteSpace: "nowrap",
  boxSizing: "border-box",
  display: "flex",
  flexDirection: "column",
  height: "100vh",
  ...(open && {
    ...openedMixin(theme),
    "& .MuiDrawer-paper": {
      ...openedMixin(theme),
      display: "flex",
      flexDirection: "column",
      height: "100vh",
    },
  }),
  ...(!open && {
    ...closedMixin(theme),
    "& .MuiDrawer-paper": {
      ...closedMixin(theme),
      display: "flex",
      flexDirection: "column",
      height: "100vh",
    },
  }),
}));

const MobileDrawer = styled(MuiDrawer)(({ theme }) => ({
  width: drawerWidth,
  flexShrink: 0,
  whiteSpace: "nowrap",
  boxSizing: "border-box",
  display: "flex",
  flexDirection: "column",
  height: "100vh",
  "& .MuiDrawer-paper": {
    width: drawerWidth,
    height: "100vh",
    display: "flex",
    flexDirection: "column",
  },
}));

const openedMixin = (theme: Theme): CSSObject => ({
  width: drawerWidth,
  transition: theme.transitions.create("width", {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.enteringScreen,
  }),
  overflowX: "hidden",
});

const closedMixin = (theme: Theme): CSSObject => ({
  transition: theme.transitions.create("width", {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  overflowX: "hidden",
  width: `calc(${theme.spacing(7)} + 1px)`,
  [theme.breakpoints.up("sm")]: {
    width: `calc(${theme.spacing(9)} + 1px)`,
  },
});

const DrawerHeader = styled("div")(({ theme }) => ({
  display: "flex",
  alignItems: "center",
  height: headerHeight,
  padding: theme.spacing(0, 1),
  backgroundColor: theme.palette.mainMenuNav.mainNavBg,
  paddingLeft: "75px",
  margin: "0px",
  ...theme.mixins.toolbar,
  justifyContent: "flex-end",
  flexShrink: 0,
}));

const DrawerContent = styled("div")(({ theme }) => ({
  backgroundColor: theme.palette.mainMenuNav.mainNavBg,
  overflowY: "auto",
  flexGrow: 1,
  height: "calc(100% - 64px)",
  "&::-webkit-scrollbar": {
    width: "4px",
  },
  "&::-webkit-scrollbar-thumb": {
    backgroundColor:
      appColors.dataBssThemeDarkMenuColorLight["--bs-main-nav-item-color"],
    borderRadius: "10px",
  },
  "&::-webkit-scrollbar-thumb:hover": {
    backgroundColor: "rgba(0, 0, 0, 0.5)",
  },
  "&::-webkit-scrollbar-track": {
    background: "transparent",
  },
}));

const PaddingBody = styled("div")(({ theme }) => ({
  height: headerHeight,
}));

export default function MiniDrawer({
  children,
}: {
  children: React.ReactNode;
}) {
  const theme = useTheme();
  const classes = useStyles();
  const [mobileDrawerOpen, setMobileDrawerOpen] = React.useState(false);
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));
  const [open, setOpen] = React.useState(true);

  const [notificationPopUp, setNotificationPopUp] =
    React.useState<HTMLElement | null>(null);
  const { mode, toggleTheme } = useThemeContext();
  const [profilePopUp, setProfilePopUp] = useState<HTMLElement | null>(null);
  const openProfilePopUp = Boolean(profilePopUp);
  const openNotificationPopUp = Boolean(notificationPopUp);


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

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

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

  const handleMobileDrawerToggle = () => {
    setMobileDrawerOpen(!mobileDrawerOpen);
  };

  const handleMobileDrawerClose = () => {
    setMobileDrawerOpen(false);
  };

  const handleClickNotificationPopUp = (
    event: React.MouseEvent<HTMLElement>
  ) => {
    setNotificationPopUp(event.currentTarget);
  };

  const handleClickProfilePopUp = (event: React.MouseEvent<HTMLElement>) => {
    setProfilePopUp(event.currentTarget);
  };

  const handleCloseProfilePopUp = () => {
    setProfilePopUp(null);
  };

  const handleCloseNotificationPopUp = () => {
    setNotificationPopUp(null);
  };

 



  return (
    <Box sx={{ display: "flex" }}>
      {!isMobile ? (
        <Box sx={{ display: "flex" }}>
          <CssBaseline />
          <AppBar position="fixed" open={open} className={classes.topbar}>
            <Toolbar className={classes.toolbar}>
              <Typography className={classes.h4}>WELCOME!</Typography>
              <Grid
                container
                data-testid="user-content"
                spacing={1}
                alignItems="center"
                justifyContent="flex-end"
                sx={{ display: "flex" }}
              >
                <Grid item>
                  <IconButton
                    onClick={handleClickNotificationPopUp}
                    className={classes.topbarButton}
                    aria-haspopup="true"
                  >
                    <MdOutlineNotificationsNone
                      className={classes.topbarIcon}
                    />
                  </IconButton>
                  <IconButton
                    onClick={toggleTheme}
                    aria-haspopup="true"
                    className={classes.topbarButton}
                  >
                    {mode == "light" ? (
                      <MdDarkMode className={classes.topbarIcon} />
                    ) : (
                      <MdDarkMode className={classes.topbarIcon} />
                    )}
                  </IconButton>
                  <IconButton
                    onClick={handleClickProfilePopUp}
                    className={classes.topbarButton}
                    aria-haspopup="true"
                  >
                    <Avatar
                      alt="Travis Howard"
                      src={UserImg}
                      className={classes.topbarIconProfile}
                    />
                  </IconButton>
                </Grid>

                <Grid item>
                  <div className={classes.appSearch}>
                    <TextField
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <CiSearch className={classes.searchWidgetIcon} />
                          </InputAdornment>
                        ),
                        classes: {
                          root: classes.formControl,
                          notchedOutline: classes.notchedOutline,
                        },
                      }}
                      fullWidth
                      placeholder="Search .."
                      variant="outlined"
                      size="small"
                    />
                  </div>
                </Grid>
              </Grid>
              <Profile
                profile={profilePopUp}
                onClose={handleCloseProfilePopUp}
                open={openProfilePopUp}
              />
              <Notification
                notification={notificationPopUp}
                onClose={handleCloseNotificationPopUp}
                open={openNotificationPopUp}
              />
            </Toolbar>
          </AppBar>
          <IsNotMobileDrawer variant="permanent" open={open}>
            <DrawerHeader>
              <IconButton
                className={classes.topbarButton}
                onClick={handleDrawerToggle}
              >
                {open ? (
                  <ChevronRightIcon className={classes.topbarIcon} />
                ) : (
                  <ChevronLeftIcon className={classes.topbarIcon} />
                )}
              </IconButton>
            </DrawerHeader>
            <DrawerContent>
              <List>
                {[
                  "Inbox",
                  "Starred",
                  "Send email",
                  "Inbox",
                  "Starred",
                  "Send email",
                  "Inbox",
                  "Starred",
                  "Send email",
                  "Inbox",
                  "Starred",
                  "Send email",
                  "Inbox",
                  "Starred",
                  "Send email",
                ].map((text, index) => (
                  <ListItem button key={text}>
                    <ListItemIcon>
                      {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
                    </ListItemIcon>
                    <ListItemText primary={text} />
                  </ListItem>
                ))}
              </List>
              <Divider />
              <List>
                {["All mail", "Trash", "Spam"].map((text, index) => (
                  <ListItem button key={text}>
                    <ListItemIcon>
                      {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
                    </ListItemIcon>
                    <ListItemText primary={text} />
                  </ListItem>
                ))}
              </List>
            </DrawerContent>
          </IsNotMobileDrawer>
        </Box>
      ) : (
        <Box sx={{ display: "flex" }}>
          <AppBar position="fixed" className={classes.mobileTopbar}>
            <Toolbar className={classes.toolbar}>
              <Grid
                container
                justifyContent="space-between"
                sx={{ width: "100%" }}
                alignItems="center"
              >
                <Grid item md={1} sm={1}>
                  <IconButton
                    onClick={handleMobileDrawerToggle}
                    edge="start"
                    sx={{
                      ...(mobileDrawerOpen && { display: "none" }),
                    }}
                    className={classes.topbarButton}
                  >
                    {mobileDrawerOpen ? (
                      <CloseIcon className={classes.topbarIcon} />
                    ) : (
                      <MenuIcon className={classes.topbarIcon} />
                    )}
                  </IconButton>
                </Grid>
                <Grid item md={2} sm={2}>
                <Typography className={classes.h4}>WELCOME!</Typography>
                </Grid>
                <Grid item md={9} sm={9} justifyContent="end" alignItems="end">
                  <Grid
                    container
                    spacing={1}
                    alignItems="end"
                    justifyContent="flex-end"
                    sx={{
                      display: "flex",
                    }}
                  >
                    <Grid item>
                      <IconButton
                        onClick={handleClickNotificationPopUp}
                        className={classes.topbarButton}
                        aria-haspopup="true"
                      >
                        <MdOutlineNotificationsNone
                          className={classes.topbarIcon}
                        />
                      </IconButton>
                      <IconButton
                        onClick={toggleTheme}
                        aria-haspopup="true"
                        className={classes.topbarButton}
                      >
                        {mode == "light" ? (
                          <MdDarkMode className={classes.topbarIcon} />
                        ) : (
                          <MdDarkMode className={classes.topbarIcon} />
                        )}
                      </IconButton>
                      <IconButton
                        onClick={handleClickProfilePopUp}
                        className={classes.topbarButton}
                        aria-haspopup="true"
                      >
                        <Avatar
                          alt="Travis Howard"
                          src={UserImg}
                          className={classes.topbarIconProfile}
                        />
                      </IconButton>
                    </Grid>

                    <Grid
                      item
                      sx={{
                        [theme.breakpoints.down("sm")]: {
                          display: "none",
                        },
                      }}
                    >
                      <div className={classes.appSearch}>
                        <TextField
                          InputProps={{
                            startAdornment: (
                              <InputAdornment position="start">
                                <CiSearch
                                  className={classes.searchWidgetIcon}
                                />
                              </InputAdornment>
                            ),
                            classes: {
                              root: classes.formControl,
                              notchedOutline: classes.notchedOutline,
                            },
                          }}
                          fullWidth
                          placeholder="Search .."
                          variant="outlined"
                          size="small"
                        />
                      </div>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>

              
              <Profile
                profile={profilePopUp}
                onClose={handleCloseProfilePopUp}
                open={openProfilePopUp}
              />
              <Notification
                notification={notificationPopUp}
                onClose={handleCloseNotificationPopUp}
                open={openNotificationPopUp}
              />
            </Toolbar>

            <>
              <MobileDrawer
                open={mobileDrawerOpen}
                onClose={handleMobileDrawerClose}
              >
                <DrawerHeader>
                  <IconButton
                    className={classes.topbarButton}
                    onClick={handleMobileDrawerClose}
                  >
                    {theme.direction === "rtl" ? (
                      <ChevronRightIcon className={classes.topbarIcon} />
                    ) : (
                      <ChevronLeftIcon className={classes.topbarIcon} />
                    )}
                  </IconButton>
                </DrawerHeader>
                <DrawerContent>
                  <Divider />
                  <List>
                    {[
                      "Inbox",
                      "Starred",
                      "Send email",
                      "Inbox",
                      "Starred",
                      "Send email",
                      "Inbox",
                      "Starred",
                      "Send email",
                      "Inbox",
                      "Starred",
                      "Send email",
                      "Inbox",
                      "Starred",
                      "Send email",
                    ].map((text, index) => (
                      <ListItem button key={text}>
                        <ListItemIcon>
                          {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
                        </ListItemIcon>
                        <ListItemText primary={text} />
                      </ListItem>
                    ))}
                  </List>
                  <Divider />
                  <List>
                    {["All mail", "Trash", "Spam"].map((text, index) => (
                      <ListItem button key={text}>
                        <ListItemIcon>
                          {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
                        </ListItemIcon>
                        <ListItemText primary={text} />
                      </ListItem>
                    ))}
                  </List>
                </DrawerContent>
              </MobileDrawer>
            </>
          </AppBar>
        </Box>
      )}

      <Box
        component="main"
        sx={{
          flexGrow: 1,
          p: 3,
          width: open ? `calc(100% - ${drawerWidth}px)` : "100%",
        }}
      >
        <PaddingBody />
        {children}
      </Box>
    </Box>
  );
}
