import '../../styles/header.css';

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  } from "../../styles/header.styles";

import type { MobileNavProps } from "../../header.types";
import { Icon } from "../../../../molecules/Icon/index";

export const MobileNav: FC<MobileNavProps> = ({ menus, isMobileNavOpen }) => {
  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 }))}>
      <ul className="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>
                  <div
                    className="tw-cursor-pointer tw-flex tw-justify-between tw-items-center tw-py-6 tw-px-4"
                    onClick={() => handleOpenMenu(index)}
                    tabIndex={0}
                    onKeyDown={(e) => onKeyDown(e, () => handleOpenMenu(index))}
                  >
                    {menu.heading && (
                      <span className="eyebrow !tw-text-gray-400">
                        {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>
  );
};
