import * as React from "react";
import { styled, useTheme, Theme, CSSObject } from "@mui/material/styles";
import Box from "@mui/material/Box";
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 Divider from "@mui/material/Divider";
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 ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import {
  Avatar,
  Collapse,
  Grid,
  InputAdornment,
  SvgIconProps,
  TextField,
  Tooltip,
  useMediaQuery,
} from "@mui/material";
import DashboardIcon from "@mui/icons-material/Dashboard";
import { useLocation, useNavigate } from "react-router-dom";
import { useEffect, useMemo, useState } from "react";
import Profile from "../../Components/Popup/profile";
import Notification from "../../Components/Popup/notification";
import { appColor } from "../../theme/appColor";
import NotificationsNoneIcon from "@mui/icons-material/NotificationsNone";
import UserImg from "../../Images/user_login_photo.webp";
import Logo from "../../Images/logo_main_white.webp";
import LogoMain from "../../Images/logo_main_black.webp";
import LoginImg from "../../Images/atto_desk_login_background.webp";
import SearchIcon from "@mui/icons-material/Search";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ExpandLessIcon from "@mui/icons-material/ExpandLess";
import SettingsIcon from "@mui/icons-material/Settings";
import InfoIcon from "@mui/icons-material/Info";
import CategoryIcon from "@mui/icons-material/Category";
import AddShoppingCartIcon from "@mui/icons-material/AddShoppingCart";
import DomainAddIcon from "@mui/icons-material/DomainAdd";
import SubjectIcon from "@mui/icons-material/Subject";
import CurrencyExchangeIcon from "@mui/icons-material/CurrencyExchange";
import ProductionQuantityLimitsIcon from "@mui/icons-material/ProductionQuantityLimits";
import PrintIcon from "@mui/icons-material/Print";
import StyleIcon from "@mui/icons-material/Style";
import ClassIcon from "@mui/icons-material/Class";
import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutline";
import PostAddIcon from "@mui/icons-material/PostAdd";
import DynamicFeedIcon from "@mui/icons-material/DynamicFeed";
import RepeatIcon from "@mui/icons-material/Repeat";
import AddIcon from "@mui/icons-material/Add";
import PeopleAltIcon from "@mui/icons-material/PeopleAlt";
import Brightness4Icon from "@mui/icons-material/Brightness4";
import Brightness7Icon from "@mui/icons-material/Brightness7";
import { useThemeContext } from "./ThemeContext";
import { MdDarkMode } from "react-icons/md";
import { useStyles } from "../../theme/appStyles";
import { MdOutlineNotificationsNone } from "react-icons/md";
import { CiSearch } from "react-icons/ci";
import { MdArrowBackIos } from "react-icons/md";
import { MdArrowForwardIos } from "react-icons/md";
import { RiArrowRightDoubleLine } from "react-icons/ri";
import { RiArrowLeftDoubleLine } from "react-icons/ri";
import { FaShopify } from "react-icons/fa";

const drawerWidth = 280;

const openedMixin = (theme: Theme): CSSObject => ({
  width: drawerWidth,
  transition: theme.transitions.create("width", {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.enteringScreen,
  }),
  overflowX: "hidden",
  backgroundColor: theme.palette.mainMenuNav.mainNavBg,
  // borderRight: "6px solid green",
  // backgroundImage: `url(${LoginImg})`,
  // backgroundSize: "cover",
  // backgroundRepeat: "no-repeat",
  // backgroundPosition: "center",
  // opacity: 0.1,
});

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(5)} + 1px)`,
  [theme.breakpoints.up("sm")]: {
    width: `calc(${theme.spacing(7)} + 1px)`,
  },
  backgroundColor: theme.palette.mainMenuNav.mainNavBg,
  // borderRight: "6px solid green",
  // backgroundImage: `url(${LoginImg})`,
  // backgroundSize: "cover",
  // backgroundRepeat: "no-repeat",
  // backgroundPosition: "center",
});

const DrawerHeader = styled("div")(({ theme }) => ({
  display: "flex",
  alignItems: "center",
  justifyContent: "flex-end",
  padding: theme.spacing(0, 1),
  // necessary for content to be below app bar
  ...theme.mixins.toolbar,
}));

interface AppBarProps extends MuiAppBarProps {
  open?: boolean;
}

const AppBar = styled(MuiAppBar, {
  shouldForwardProp: (prop) => prop !== "open",
})<AppBarProps>(({ theme, open }) => ({
  zIndex: theme.zIndex.drawer + 1,
  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 Drawer = styled(MuiDrawer, {
  shouldForwardProp: (prop) => prop !== "open",
})(({ theme, open }) => ({
  width: drawerWidth,
  flexShrink: 0,
  whiteSpace: "nowrap",
  boxSizing: "border-box",
  ...(open && {
    ...openedMixin(theme),
    "& .MuiDrawer-paper": openedMixin(theme),
  }),
  ...(!open && {
    ...closedMixin(theme),
    "& .MuiDrawer-paper": closedMixin(theme),
  }),
}));

type SubmenuItem = {
  title: string;
  path: string;
  newPage?: boolean;
  icon: React.ReactElement;
};

const menuList: {
  title: string;
  icon: SvgIconProps;
  path: string;
  newPage?: boolean;
  submenuOpen?: boolean;
  submenus?: SubmenuItem[];
}[] = [
  {
    title: "Products",
    icon: <AddIcon />,
    path: "/setting",
    submenuOpen: true,
    submenus: [
      {
        title: "Product",
        icon: <ProductionQuantityLimitsIcon />,
        path: "/product",
      },
      {
        title: "Category",
        icon: <CategoryIcon />,
        path: "/category",
      },
      // {
      //   title: "Sub Category",
      //   icon: <ClassIcon />,
      //   path: "/sub-category",
      // },
      {
        title: "Looping",
        icon: <RepeatIcon />,
        path: "/looping",
      },
      {
        title: "Department",
        icon: <DomainAddIcon />,
        path: "/department",
      },
      {
        title: "Coursing",
        icon: <SubjectIcon />,
        path: "/coursing",
      },
      {
        title: "Product Brand",
        icon: <CheckCircleOutlineIcon />,
        path: "/product/brand",
      },
      {
        title: "Product Tag",
        icon: <StyleIcon />,
        path: "/product/tag",
      },
      {
        title: "Modifier",
        icon: <PostAddIcon />,
        path: "/modifier",
      },
      {
        title: "Modifier Group",
        icon: <DynamicFeedIcon />,
        path: "/modifier-group",
      },
    ],
  },
  {
    title: "Setting",
    icon: <SettingsIcon />,
    path: "/setting",
    submenuOpen: true,
    submenus: [
      {
        title: "Company Info",
        icon: <InfoIcon />,
        path: "/company-info",
      },
      {
        title: "Taxes",
        icon: <CurrencyExchangeIcon />,
        path: "/taxes",
      },
      {
        title: "Printer",
        icon: <PrintIcon />,
        path: "/printer",
      },
    ],
  },
  {
    title: "Customer",
    icon: <PeopleAltIcon />,
    path: "/customer",
    submenuOpen: false,
  },
];

export default function MiniDrawer({
  children,
}: {
  children: React.ReactNode;
}) {
  const theme = useTheme();
  const classes = useStyles();
  const [currentMenuName, setCurrentMenuName] = React.useState("");
  const [hoveredMenuName, setHoveredMenuName] = React.useState("");
  const [expandMenu, setExpandMenu] = React.useState<string>("");
  const { mode, toggleTheme } = useThemeContext();
  const [open, setOpen] = React.useState(true);
  const navigate = useNavigate();
  const location = useLocation();

  // Scroll to top on menu change
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [currentMenuName]);

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

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

  const handleClick = () => {
    navigate("/expense/list");
  };

  const isSmall = useMediaQuery(theme.breakpoints.down("sm"));
  const [profilePopUp, setProfilePopUp] = useState<HTMLElement | null>(null);
  const [notificationPopUp, setNotificationPopUp] =
    useState<HTMLElement | null>(null);
  const openProfilePopUp = Boolean(profilePopUp);
  const openNotificationPopUp = Boolean(notificationPopUp);

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

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

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

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

  const handleMainMenuItemClick = (ml: (typeof menuList)[0]) => {
    if (isSmall) {
      // handle small screen logic here
    }

    if (ml.submenus && ml.submenus.length > 0) {
      ml.title === expandMenu ? setExpandMenu("") : setExpandMenu(ml.title);
    } else if (ml.path) {
      setCurrentMenuName(ml.path);
      navigate(ml.path);
    }
  };

  const handleSubmenuItemClicked = (submenu: SubmenuItem) => {
    setCurrentMenuName(submenu.path);
    navigate(submenu.path);
  };

  return (
    <Box sx={{ display: "flex" }}>
      <CssBaseline />
      <AppBar position="fixed" open={open} className={classes.topbar}>
        <Toolbar className={classes.toolbar}>
          <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 sx={{ pb: 1 }}>
              <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>
      <Drawer
        variant="permanent"
        open={open}
      >
        <DrawerHeader>
          <ListItem onClick={handleClick} >
            <img
              src={LogoMain}
              alt="AttoDesk Login"
              style={{
                width: "100%",
                height: "auto",
                display: "block",
                cursor: "pointer",
              }}
              onClick={handleClick}
            />
            <IconButton
              onClick={open ? handleDrawerClose : handleDrawerOpen}
              className={classes.topbarButton}
            >
              {open ? (
                <RiArrowRightDoubleLine className={classes.topbarIcon} />
              ) : (
                <RiArrowLeftDoubleLine className={classes.topbarIcon} />
              )}
            </IconButton>
          </ListItem>
        </DrawerHeader>

        <List>
          {menuList.map((ml, index) => (
            <React.Fragment key={index}>
            <Typography>General</Typography>
           
            
            <ListItem
              key={ml.title}
              disablePadding
              sx={{
                display: "block",
                background: currentMenuName === ml.path ? "green" : "none",
              }}
              onMouseEnter={() => setHoveredMenuName(ml.path)}
              onMouseLeave={() => setHoveredMenuName("")}
            >
              <ListItemButton
                onClick={() => handleMainMenuItemClick(ml)}
                sx={{
                  "& .MuiListItemIcon-root": {
                    minWidth: "auto",
                    mr: 2,
                  },
                }}
              >
                <ListItemIcon
                  sx={{
                    color:
                      currentMenuName === ml.path
                        ? appColor.white
                        : appColor.white,
                  }}
                >
                  {ml.icon as React.ReactNode}
                </ListItemIcon>
                <ListItemText>
                  <Typography
                    // variant="h5"
                    sx={{
                      color:
                        currentMenuName === ml.path
                          ? appColor.white
                          : appColor.white,
                    }}
                  >
                    {ml.title}
                  </Typography>
                </ListItemText>
                {ml.submenus &&
                  (expandMenu === ml.title ? (
                    <ExpandLessIcon
                      sx={{
                        color:
                          currentMenuName === ml.path
                            ? appColor.white
                            : appColor.white,
                        ml: 2,
                      }}
                    />
                  ) : (
                    <ExpandMoreIcon
                      sx={{
                        color:
                          currentMenuName === ml.path
                            ? appColor.white
                            : appColor.white,
                        ml: 2,
                      }}
                    />
                  ))}
              </ListItemButton>
              {ml.submenus && (
                <Collapse
                  in={expandMenu === ml.title}
                  timeout="auto"
                  unmountOnExit
                >
                  <List>
                    {ml.submenus.map((submenu) => (
                      <ListItem
                        disablePadding
                        key={submenu.title}
                        sx={{
                          color: appColor.white,
                          background:
                            currentMenuName === submenu.path ? "green" : "none",
                        }}
                      >
                        <ListItemButton
                          onClick={() => handleSubmenuItemClicked(submenu)}
                          sx={{ ml: 0.6 }}
                        >
                          <ListItemIcon
                            sx={{
                              color:
                                currentMenuName === submenu.path
                                  ? appColor.white
                                  : appColor.white,
                            }}
                          >
                            {submenu.icon as React.ReactNode}
                          </ListItemIcon>
                          <ListItemText>
                            <Typography
                              // variant="h5"
                              sx={{
                                color:
                                  currentMenuName === submenu.path
                                    ? appColor.white
                                    : appColor.white,
                              }}
                            >
                              {submenu.title}
                            </Typography>
                          </ListItemText>
                        </ListItemButton>
                      </ListItem>
                    ))}
                  </List>
                </Collapse>
              )}
            </ListItem>
            </React.Fragment>
          ))}
        </List>
      </Drawer>
      <Box component="main" sx={{ flexGrow: 1, p: 3 }}>
        <DrawerHeader />
        {children}
      </Box>
    </Box>
  );
}
