import React, { useState } from "react";

import type { FC } from "react";

import { MobileMenuItem } from "./MobileMenuItem";

import { onKeyDown } from "../../../../utils/onKeyDown";

import { cssMerge } from "../../../../utils/cssMerge";

import { navIconStyling, mobileNavMenuStyling, topLevelMenuItem } from "../header.styles";

import type { MobileNavProps } from "../../header.types";
import { Icon } from "../../../../molecules/Icon/index";
import { isActiveParent } from '../../utils/functions';

export const MobileNav: FC<MobileNavProps> = ({ menus, isMobileNavOpen, className }) => {
  const [openMobileMenu, setOpenMobileMenu] = useState<number | null>(null);

  const handleOpenMenu = (menuIndex: number) => {
    if (openMobileMenu === menuIndex) {
      return setOpenMobileMenu(null);
    }
    setOpenMobileMenu(menuIndex);
  };

  return (
    <div className={cssMerge(mobileNavMenuStyling({ isOpen: isMobileNavOpen, className }))}>
      <ul className="!tw-pl-0 !tw-list-none tw-flex tw-flex-col tw-overflow-auto">
        {menus &&
          menus.map((menu, index: number) => {
            if (!menu) {
              return null;
            }
            const isOpen = index === openMobileMenu;
            const menuItems = menu && menu.menuItems;

            return (
              <li key={index}>
                <div
                  className={cssMerge("tw-cursor-pointer tw-flex tw-justify-between tw-items-center tw-py-6 tw-px-4", topLevelMenuItem({ active: isActiveParent(menu) }))}
                  onClick={() => handleOpenMenu(index)}
                  tabIndex={0}
                  onKeyDown={(e) => onKeyDown(e, () => handleOpenMenu(index))}
                >
                  {menu.heading && (
                    <span className="tw-text-sm">
                      {menu.heading}
                    </span>
                  )}
                  <Icon
                    id="chevron"
                    className={cssMerge(navIconStyling({ isOpen }))}
                    stroke="currentColor"
                    size={12}
                  />
                </div>
                <div className="tw-flex tw-flex-col tw-gap-3 tw-border tw-rounded-lg tw-border-gray-900">
                  {isOpen && menuItems &&
                    menuItems.map((menuItem, index) => {
                      const isLast = menuItems.length - 1 === index;

                      return (
                        <MobileMenuItem
                          key={index}
                          {...menuItem}
                          iconColor={menu.colorScheme}
                          isLast={isLast}
                        />
                      );
                    })}
                </div>
              </li>
            );
          })}
      </ul>
    </div>
  );
};
