import React from "react";

import { MaterialIcon } from "@shared/components/material-icon";
import { Button } from "@shared/contentful/blocks/button";
import { ButtonProps as ContentfulButtonProps } from "@shared/contentful/blocks/button/types";

type ComponentButtonGroup = {
  anchorId?: string | null;
  title?: string | null;
  items?: { items?: ContentfulButtonProps[] | null } | null;
};

type Link = ContentfulButtonProps | ComponentButtonGroup;

type LinkGroupsProps = {
  link?: Link;
};

const isButton = (link: Link): link is ContentfulButtonProps => {
  // If your group never has `href`, this is a simple and effective guard
  return typeof (link as ContentfulButtonProps).href === "string";
};

export const MobileLinkGroups: React.FC<LinkGroupsProps> = ({ link }) => {
  const [isOpen, setIsOpen] = React.useState(false);
  if (!link) return null;

  // Single button
  if (isButton(link)) {
    return (
      <Button
        key={`submenu-link-btn-${link.anchorId}`}
        {...link}
        linkClassName="label3 flex items-center w-full h-11 px-4 text-text-link"
        linkVariant="unstyled"
      />
    );
  }

  // Group
  const { anchorId, title, items } = link;
  const subMenu = Array.isArray(items?.items) ? items!.items! : [];

  return (
    <>
      <Button
        onClick={() => setIsOpen(prev => !prev)}
        aria-expanded={isOpen}
        buttonClassName=" label3 flex items-center w-full h-11 px-4"
        key={anchorId}
        showButtonAs="unstyled"
      >
        {title ?? null}
        <MaterialIcon
          weight="200"
          size={24}
          className="group-hover:opacity-50 text-icon-secondary"
          name={isOpen ? "keyboard_arrow_up" : "keyboard_arrow_down"}
        />
      </Button>
      {isOpen && subMenu.length > 0 && <RenderSubMenu items={subMenu} />}
    </>
  );
};

const RenderSubMenu: React.FC<{ items: ContentfulButtonProps[] }> = ({
  items,
}) => (
  <ul key={`submenu-${items.length}`} className="flex flex-col gap-2">
    {items.map((site, index) => {
      return (
        <li key={`submenu-link-${index}`} className="submenu-link type2">
          <Button
            {...site}
            linkVariant="unstyled"
            linkClassName="body3 pl-8 pr-4 flex items-center w-full h-11 text-text-link"
          />
        </li>
      );
    })}
  </ul>
);
