import styles from "./MobileMenu.module.css";
import { Fragment, MouseEvent, useEffect, useRef } from "react";
import { useContext, useState } from "react";
import NextLink from "next/link";
import { AppContext } from "@/contexts/AppContext";
import { extractPath } from "@/components/Menu/Menu";
import Social from "@/components/Social/Social";
import { usePathname } from "next/navigation";
import { CONTACT_PATH } from "@/utils/constants";

const FLYOUT_CLOSE_DURATION_MS = 1200;

const MobileMenu = (props: any) => {
  const subMenuRef = useRef(null);
  const appContext = useContext(AppContext);
  const pathname = usePathname();
  const isContactPage = pathname === CONTACT_PATH;

  const [activeMenuItem, setActiveMenuItem] = useState<number | boolean>(false);
  const hasNavigableUrl = (url: string) => !!url && url !== "#";

  const handleClick = (e: MouseEvent, item: any) => {
    e.stopPropagation();

    if (item.children) {
      e.preventDefault();
      setActiveMenuItem(Number(item.ID));
      return;
    }

    props.closeMenu(e, item.url);
  };

  useEffect(() => {
    if (appContext.state.showMenu) {
      return;
    }

    const resetTimer = window.setTimeout(() => {
      setActiveMenuItem(false);

      if (subMenuRef.current) {
        // @ts-ignore
        subMenuRef.current.scroll({
          top: 0,
          behavior: "smooth",
        });
      }
    }, FLYOUT_CLOSE_DURATION_MS);

    return () => window.clearTimeout(resetTimer);
  }, [appContext.state.showMenu]);

  const renderChildItem = (child: any, animateIn: boolean) => (
    <ul
      key={child.ID}
      className={`${styles.mobile_menu__sub_item} ${
        animateIn ? "" : styles.staggered_slide_right
      }`}
    >
      <li>
        <NextLink
          href={extractPath(child.url)}
          className="block h2 capitalize"
          onClick={(e) => props.closeMenu(e, child.url)}
        >
          {child.title}
        </NextLink>
        {child.children && (
          <ul className="list-none p-none m-none">
            {Object.values(child.children).map((grandChild: any) => (
              <li key={grandChild.ID}>
                <NextLink
                  href={extractPath(grandChild.url)}
                  className="font-light h5 block"
                  onClick={(e) => props.closeMenu(e, grandChild.url)}
                >
                  {grandChild.title}
                </NextLink>
                {grandChild.children && (
                  <ul className={styles.grandGrandChild}>
                    {Object.values(grandChild.children).map(
                      (grandGrandChild: any) => (
                        <li key={grandGrandChild.ID}>
                          <NextLink
                            href={extractPath(grandGrandChild.url)}
                            className="font-light h5 block pl-4"
                            onClick={(e) =>
                              props.closeMenu(e, grandGrandChild.url)
                            }
                          >
                            {grandGrandChild.title}
                          </NextLink>
                        </li>
                      ),
                    )}
                  </ul>
                )}
              </li>
            ))}
          </ul>
        )}
      </li>
    </ul>
  );

  const renderTopLevelMenu = () => (
    <div
      className={`${styles.mobile_menu__top_level} ${
        !activeMenuItem ? styles.is_active : ""
      }`}
    >
      {Object.values(appContext.state.menu)
        .filter((item: any) => item && item.ID && item.url)
        .map((item: any) => (
          <div
            key={item.ID}
            className={`${styles.mobile_menu__top_item} ${
              !activeMenuItem ? "" : `${styles.staggered_slide_left}`
            }`}
          >
            <NextLink
              href={extractPath(item.url)}
              className={`${styles.mobile_menu__link} h1`}
              onClick={(e) => handleClick(e, item)}
              aria-expanded={
                item.children ? activeMenuItem === Number(item.ID) : undefined
              }
            >
              {item.title}
              {item.children && (
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  height="32"
                  viewBox="0 -960 960 960"
                  width="32"
                >
                  <path d="M647-440H160v-80h487L423-744l57-56 320 320-320 320-57-56 224-224Z" />
                </svg>
              )}
            </NextLink>
          </div>
        ))}
      {!isContactPage && (
        <div className={styles.mobile_menu__top_item}>
          <NextLink
            href={CONTACT_PATH}
            className={`${styles.mobile_menu__link} h1 text-white`}
            onClick={(e) => props.closeMenu(e, CONTACT_PATH)}
          >
            Contact
          </NextLink>
        </div>
      )}
      <div className={styles.mobile_menu__footer}>
        {/* <NextLink href="#" className="block mb-xs">
          Support login
        </NextLink> */}
        <Social inverted={true} />
      </div>
    </div>
  );

  const renderSubMenus = () =>
    Object.values(appContext.state.menu)
      .filter((item: any) => item && item.ID && item.url)
      .map((item: any) => (
        <Fragment key={item.ID}>
          {item.children && (
            <div
              ref={
                activeMenuItem === Number(item.ID) ? subMenuRef : undefined
              }
              className={`${styles.mobile_menu__sub_menu} ${
                activeMenuItem === Number(item.ID) ? styles.is_active : ""
              }`}
            >
              <button
                type="button"
                className={`${styles.mobile_menu__back} hover:text-white`}
                onClick={(e) => {
                  e.stopPropagation();
                  setActiveMenuItem(false);
                }}
              >
                <svg
                  className={styles.mobile_menu__back_icon}
                  xmlns="http://www.w3.org/2000/svg"
                  height="16"
                  viewBox="0 -960 960 960"
                  width="16"
                  aria-hidden="true"
                >
                  <path d="m313-440 224 224-57 56-320-320 320-320 57 56-224 224h487v80H313Z" />
                </svg>
                Go back
              </button>
              {hasNavigableUrl(item.url) && (
                <NextLink
                  href={extractPath(item.url)}
                  className="block h3 mb-[1.25rem]"
                  onClick={(e) => props.closeMenu(e, item.url)}
                >
                  View all {item.title}
                </NextLink>
              )}
              {Object.values(item.children).map((child) =>
                renderChildItem(child, activeMenuItem === Number(item.ID)),
              )}
            </div>
          )}
        </Fragment>
      ));

  return (
    <div className={styles.mobile_menu}>
      <div className={styles.mobile_menu__wrapper}>
        {renderTopLevelMenu()}
        {renderSubMenus()}
      </div>
    </div>
  );
};

export default MobileMenu;
