import Link from "next/link";
import style from "./navbar.module.css";
import { useRouter } from "next/router";
import { useEffect, useMemo, useState } from "react";
import { useWindowSize } from "@/customHook/useWindowSize";
import { useDispatch, useSelector } from "react-redux";
import { accountStoreActions } from "@/store/account";
import { authApi } from "@/api/api";
import { productStoreActions } from "@/store/forms";
import {
  Gavel,
  List,
  Logout,
  ManageAccounts,
  Markunread,
  Menu,
  MenuOpen,
  PhoneAndroid,
  PrivacyTip,
  RemoveShoppingCart,
  Sell,
  ShoppingBagOutlined,
} from "@mui/icons-material";
import MenuDrawer from "@/components/utils/menuDrawer";

const Navbar = (props) => {
  const router = useRouter();
  const { width } = useWindowSize();
  const loggedIn = useSelector((state) => state.accountStore.loggedIn);
  const dispatch = useDispatch();
  const account = useSelector((state) => state.accountStore);
  const [mobileView, setMobileView] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [accountMenu] = useState([
    {
      name: "My Orders",
      path: "/account/orders",
      icon: <ShoppingBagOutlined />,
    },
    {
      name: "My Return",
      path: "/account/returned",
      icon: <RemoveShoppingCart />,
    },
    {
      name: "Address",
      path: "/account/address",
      icon: <Markunread />,
    },
    {
      name: "Profile",
      path: "/account/profile",
      icon: <ManageAccounts />,
    },
  ]);
  let defaultMenu = [
    { name: "Shop", path: "/store" },
    { name: "Our Story", path: "/our-story" },
    { name: "Contact", path: "/contact-us" },
    { name: "Become A Seller", path: "/become-a-seller" },
    {
      name: "Seller Account",
      path:
        process.env.NEXT_PUBLIC_ECMANAGER +
        "/reseller/login?company=65df077d5ed624e07dd21220",
      newTab: true,
    },
  ];
  const onLogout = async () => {
    const result = await authApi.post(
      "/customer/logout",
      {},
      {
        withCredentials: true,
      }
    );
    window.location.href = "/";
  };
  const [menu, setMenu] = useState(defaultMenu);
  useMemo(() => {
    console.log("width: ", width);

    setMobileView(true);
    const extraMenu = [
      {
        name: "Privacy Policy",
        path: "/privacy-policy",
        icon: <PrivacyTip />,
      },
      {
        name: "Terms & Conditions",
        path: "/terms-and-conditions",
        icon: <Gavel />,
      },
      {
        name: "Shipping Policy",
        path: "/shipping-policy",
        icon: <Gavel />,
      },
    ];
    setMenu(() => {
      const newArray = [
        { name: "Home", path: "/" },
        ,
        ...defaultMenu,
        ...extraMenu,
      ];
      return newArray;
    });
  }, [width]);

  const Header = () => {
    return (
      <div className={style.menu_drawer_header}>
        {loggedIn ? (
          <div className={style.loggedInText}>Welcome, {account.name}</div>
        ) : (
          <div className={style.menu_header_text}>
            <button
              type="button"
              onClick={() => dispatch(accountStoreActions.openSignInUI())}
            >
              Login
            </button>
            /
            <button
              type="button"
              onClick={() => dispatch(accountStoreActions.openSignUpUI())}
            >
              Register
            </button>
          </div>
        )}
      </div>
    );
  };

  return (
    <div className={style.navbar}>
      {mobileView && (
        <div
          className={style.mobile_menu}
          onClick={() => setMenuOpen((prev) => !prev)}
        >
          {!menuOpen ? <Menu /> : <MenuOpen />}
        </div>
      )}
      {mobileView ? (
        <MenuDrawer
          open={menuOpen}
          onClose={() => setMenuOpen(false)}
          title={<Header />}
        >
          <div className={style.menu_drawer_section}>
            {loggedIn && (
              <ul className={style.menu_main_section}>
                <h2 className={style.menu_title}>Account</h2>
                {accountMenu.map((item) => (
                  <li
                    className={`${
                      router.pathname.substring(
                        router.pathname.indexOf("/"),
                        router.pathname.length
                      ) == item.path
                        ? style.active
                        : ""
                    } ${style.menu_section}`}
                    key={item.name}
                  >
                    <Link href={item.path} onClick={() => setMenuOpen(false)}>
                      {/* {item.icon && item.icon} */}
                      {item.name}
                    </Link>
                  </li>
                ))}
              </ul>
            )}
            {/* Other Menu Section */}
            <ul className={style.menu_main_section}>
              <h2 className={style.menu_title}>Other</h2>
              {menu.map((item) => (
                <li
                  className={`${
                    "/" + router.pathname.split("/")[1].split("/")[0] ==
                    item.path
                      ? style.active
                      : ""
                  } ${style.menu_section}`}
                  key={item.name}
                >
                  <Link
                    href={item.path}
                    onClick={() => setMenuOpen(false)}
                    target={item.newTab ? "_blank" : ""}
                  >
                    {/* {item.icon && item.icon} */}
                    {item.name}
                  </Link>
                </li>
              ))}
              {loggedIn && (
                <>
                  <li className={style.menu_section}>
                    <Link href="/logout">Logout</Link>
                  </li>
                </>
              )}
            </ul>
          </div>
        </MenuDrawer>
      ) : (
        <ul className={style.menu_main_section}>
          {menu.map((item) => (
            <li
              className={`${
                "/" + router.pathname.split("/")[1].split("/")[0] == item.path
                  ? style.active
                  : ""
              } ${style.menu_section}`}
              key={item.name}
            >
              <Link href={item.path} onClick={() => setMenuOpen(false)}>
                {/* {item.icon && item.icon} */}
                {item.name}
              </Link>
            </li>
          ))}
          {loggedIn && (
            <>
              <li className={style.menu_section}>
                <Link href="/logout">Logout</Link>
              </li>
            </>
          )}
        </ul>
      )}
    </div>
  );
};

export default Navbar;
