import React, { useContext, useEffect, useState } from "react";
import {
  Bar,
  MainHeader,
  Text,
  Textlink,
  useStyles,
  NavigationBar,
  Mobilemenu,
  HeaderRightMenu,
  NotificationButton,
  UserDetail,
  UserEmail,
  FullContent,
} from "./style";
import { Box, Toolbar } from "@mui/material";
import MenuRoundedIcon from "@mui/icons-material/MenuRounded";
import Drawer from "@mui/material/Drawer";
import Button from "@mui/material/Button";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemText from "@mui/material/ListItemText";
import router, { useRouter } from "next/router";
import Avatar from "@mui/material/Avatar";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import ListItemIcon from "@mui/material/ListItemIcon";
import Divider from "@mui/material/Divider";
import IconButton from "@mui/material/IconButton";
import Tooltip from "@mui/material/Tooltip";
import PersonAdd from "@mui/icons-material/PersonAdd";
import Settings from "@mui/icons-material/Settings";
import Logout from "@mui/icons-material/Logout";
import NotificationsNoneTwoToneIcon from "@mui/icons-material/NotificationsNoneTwoTone";
import { MyAppContext } from "@/contextApi/appContext";
import Auth from "@/auth/Auth";
import ProductDrawer from "./HeaderDrawer/ProductDrawer";
import { useDispatch } from "react-redux";
import { HeaderList, setUnit } from "@/hooks/HeaderHooks";
import TemporaryDrawer from "@/components/sidebar/TemporaryDrawer";
import { apiClient } from "../common";
import { AddUnitList } from "@/hooks/productDetailsReducer";
import { setUserBasicInfo } from "@/hooks/appReducers";
import { API_CDN_URL } from "@/utils/staticValues";
type Anchor = "top" | "left" | "bottom" | "right";
const HeaderPage = () => {
  const [drawer, setDrawer] = useState<boolean>(false);
  const [anchor, setAnchor] = useState<any>("");
  const [active, setActive] = useState<string>("home");
  const { asPath } = useRouter();
  const asPathNew = asPath.replace("/", "");
  const { classes } = useStyles();
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);
  const NavigateHandler = (route) => router.push(route);
  const [state, setState] = React.useState({
    top: false,
    left: false,
    bottom: false,
    right: false,
  });

  const dispatch = useDispatch();

  // useEffect(() => {
  //   dispatch(HeaderList());
  // }, []);

  const toggleDrawer =
    (anchor: Anchor, open: boolean) =>
      (event: React.KeyboardEvent | React.MouseEvent) => {
        if (
          event.type === "keydown" &&
          ((event as React.KeyboardEvent).key === "Tab" ||
            (event as React.KeyboardEvent).key === "Shift")
        ) {
          return;
        }
        setState({ ...state, [anchor]: open });
      };

  /********** Menu list option ***********/
  const [anchorMenu, setAnchorMenu] = React.useState(null);
  const [menuData, setMenuData] = React.useState<any>([]);
  const openMenu = Boolean(anchorMenu);
  const handleMenuClick = (event) => {
    setAnchorMenu(event.currentTarget);
  };
  const handleMenuClose = () => {
    setAnchorMenu(null);
  };

  useEffect(() => {
    setMenuData(JSON.parse(localStorage?.getItem("userData")));
  }, []);

  /********** Menu list option ***********/

  const list = (anchor: Anchor) => (
    <Box
      sx={{ width: anchor === "top" || anchor === "bottom" ? "auto" : 250 }}
      role="presentation"
      onClick={toggleDrawer(anchor, false)}
      onKeyDown={toggleDrawer(anchor, false)}
    >
      <List>
        {[
          { name: "Home", url: "", active: "home" },
          { name: "About Us", url: "about-us", active: "about-us" },
          { name: "Our Products", url: null, active: "category" },
          { name: "Contact Us", url: "contact-us", active: "contact-us" },
        ].map(({ name, url }, v: any) => (
          <ListItem
            key={name}
            disablePadding
            onClick={(e) => {
              setActive(active);
              if (url == null) {
                setActive("category");
                setAnchor(e.currentTarget);
                setDrawer(true);
              }
              if (url != null) router.push(`/${url}`);
            }}
          >
            <ListItemButton>
              <ListItemText primary={name} />
            </ListItemButton>
          </ListItem>
        ))}
      </List>
    </Box>
  );
  let openDrawer = Boolean(anchor);
  useEffect(() => {
    if (asPath === "/") setActive("home");
    if (asPath === "/about-us") setActive("about-us");
    if (asPath === "/contact-us") setActive("contact-us");
  }, [asPath]);
  useEffect(() => {
    if (active === "category" && !openDrawer) {
      if (asPath === "/") setActive("home");
      if (asPath === "/about-us") setActive("about-us");
      if (asPath === "/contact-us") setActive("contact-us");
    }
  }, [openDrawer, asPath]);

 

  const fetchUnits = async () => {
    try{
       const res = await fetch(`${API_CDN_URL}/cache/unitsData.json`);
      const data = await res.json();
      dispatch(setUnit(data.data));
      dispatch(AddUnitList(data.data));
    } catch {
      let response = await apiClient("unit", "get");
    if (response?.data) {
      dispatch(setUnit(response?.data));
      dispatch(AddUnitList(response?.data));
    }
    }
    
  };

   useEffect(() => {
    fetchUnits();
  }, []);

  return (
    <>
      {openDrawer && (
        <ProductDrawer
          drawer={openDrawer}
          handleClose={() => setAnchor(null)}
          anchor={anchor}
        />
      )}
      <MainHeader
        className={asPathNew ? classes.homeheader : classes.homeheaderimg}
      >
        <Bar position="static">
          <Toolbar>
            <Box>
              <TemporaryDrawer />
            </Box>
            <FullContent>
              <Box
                onClick={() => {
                  if (asPath !== "/") router.push("/");
                }}
                style={{ cursor: "pointer" }}
              >
                <img
                  className={classes.logoimage}
                  src="/assets/PowerCozmoLogo-1.png"
                  alt="logo"
                />
              </Box>
              <NavigationBar>
                <Text>
                  <Textlink
                    href="/"
                    className={
                      active === "home" && asPath == "/" ? "active" : ""
                    }
                    onClick={() => {
                      setActive("home");
                      router.push("/");
                    }}
                  >
                    Home
                  </Textlink>
                </Text>
                <Text>
                  <Textlink
                    href="/about-us"
                    className={
                      active === "about-us" && asPath == "/about-us"
                        ? "active"
                        : ""
                    }
                    onClick={() => {
                      setActive("about-us");
                      router.push("/about-us");
                    }}
                  >
                    About Us{" "}
                  </Textlink>
                </Text>
                <Text>
                  <Textlink
                    className={active == "category" ? "active" : ""}
                    onClick={(e) => {
                      setActive("category");
                      setAnchor(e.currentTarget);
                      setDrawer(true);
                    }}
                  >
                    Our Products{" "}
                  </Textlink>
                </Text>
                <Text>
                  <Textlink
                    className={
                      active == "contact-us" && asPath == "/contact-us"
                        ? "active"
                        : ""
                    }
                    href="/contact-us"
                    onClick={() => {
                      setActive("contact-us");
                      router.push("/contact-us");
                    }}
                  >
                    Contact Us{" "}
                  </Textlink>
                </Text>
                <Text>
                  <Textlink
                    className={active == "contact-us" ? "active" : ""}
                    onClick={(e) => {
                      setActive("contact-us");

                      router.push("/contact-us");
                    }}
                  ></Textlink>
                </Text>
              </NavigationBar>
              <Mobilemenu>
                <Button onClick={toggleDrawer("right", true)}>
                  <MenuRoundedIcon className={classes.hammenu} />
                </Button>
                <Drawer
                  anchor={"right"}
                  open={state["right"]}
                  onClose={toggleDrawer("right", false)}
                >
                  {list("right")}
                </Drawer>
              </Mobilemenu>
              <HeaderRightMenu>
                {menuData?.name && (
                  <>
                    <Box
                      sx={{
                        display: "flex",
                        alignItems: "center",
                        textAlign: "center",
                      }}
                    >
                      <NotificationButton style={{ color: "#000" }}>
                        <NotificationsNoneTwoToneIcon
                          onClick={() => NavigateHandler("/notifications")}
                        />
                      </NotificationButton>
                      <Tooltip title="Account settings">
                        <IconButton
                          onClick={handleMenuClick}
                          size="small"
                          sx={{ ml: 1 }}
                          aria-controls={open ? "account-menu" : undefined}
                          aria-haspopup="true"
                          aria-expanded={open ? "true" : undefined}
                        >
                          <Avatar
                            alt="Remy Sharp"
                            src={
                              menuData?.avatar_original ||
                              "/assets/user-image.svg"
                            }
                            sx={{ width: 24, height: 24 }}
                          />
                        </IconButton>
                      </Tooltip>
                    </Box>
                    <Menu
                      anchorEl={anchorMenu}
                      id="account-menu"
                      open={openMenu}
                      onClose={handleMenuClose}
                      onClick={handleMenuClose}
                      PaperProps={{
                        elevation: 0,
                        sx: {
                          overflow: "visible",
                          filter: "drop-shadow(0px 2px 8px rgba(0,0,0,0.32))",
                          mt: 1.5,
                          "& .MuiAvatar-root": {
                            width: 32,
                            height: 32,
                            ml: -0.5,
                            mr: 1,
                          },
                          "&:before": {
                            content: '""',
                            display: "block",
                            position: "absolute",
                            top: 0,
                            right: 14,
                            width: 10,
                            height: 10,
                            bgcolor: "background.paper",
                            transform: "translateY(-50%) rotate(45deg)",
                            zIndex: 0,
                          },
                          "&.MuiMenu-paper": {
                            minWidth: "200px",
                          },
                        },
                      }}
                      transformOrigin={{ horizontal: "right", vertical: "top" }}
                      anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
                    >
                      <Box>
                        <UserDetail>
                          {menuData?.name || "Loading..."}
                        </UserDetail>
                        <UserEmail>{menuData?.email || "Loading..."}</UserEmail>
                      </Box>
                      <Divider />
                      <MenuItem onClick={() => NavigateHandler("/profile/")}>
                        <ListItemIcon>
                          <PersonAdd fontSize="small" />
                        </ListItemIcon>
                        Profile
                      </MenuItem>
                      <MenuItem onClick={() => NavigateHandler("/preferences")}>
                        <ListItemIcon>
                          <Settings fontSize="small" />
                        </ListItemIcon>
                        Settings
                      </MenuItem>
                      <Divider />
                      <MenuItem
                        onClick={(e) => {
                          Auth.logout();
                          dispatch(setUserBasicInfo({}));
                          window.location.href = "/user/signin";
                        }}
                      >
                        <ListItemIcon>
                          <Logout fontSize="small" />
                        </ListItemIcon>
                        Logout
                      </MenuItem>
                    </Menu>
                  </>
                )}
              </HeaderRightMenu>
            </FullContent>
          </Toolbar>
        </Bar>
      </MainHeader>
    </>
  );
};
export default HeaderPage;
