import { createSlug } from "@/utils/general";
import { cn } from "@/utils/style";
import { FC, Fragment, PropsWithChildren } from "react";

type HeaderDropdownProps = {
  className?: string;
};

export const HeaderDropdown: FC<PropsWithChildren<HeaderDropdownProps>> = ({ children, className }) => {
  return <ul className={cn("rd-menu rd-navbar-megamenu", className)}>{children}</ul>;
};

type HeaderDropdownGroupProps = {
  title?: string;
  className?: string;
};

export const HeaderDropdownGroup: FC<PropsWithChildren<HeaderDropdownGroupProps>> = ({
  children,
  title,
  className,
}) => {
  return (
    <li className={cn("rd-megamenu-item", className)}>
      {!!title && <h6 className="rd-megamenu-title">{title}</h6>}
      {children}
    </li>
  );
};

type HeaderDropdownMenuItem = { title: string; href?: string };
type HeaderDropdownMenuItemWithChild = { title: string; child: HeaderDropdownMenuItem[] };

type HeaderDropdownMenuProps = {
  list?: (HeaderDropdownMenuItem | HeaderDropdownMenuItemWithChild)[];
};

export const HeaderDropdownMenu: FC<HeaderDropdownMenuProps> = ({ list = [] }) => {
  return (
    <ul className="rd-megamenu-list">
      {list.map((item, idx) => {
        const collapseId = createSlug(`collapse-${item.title}-${idx}`);
        const hasChild = "child" in item;
        const hrefClass = hasChild || !!item?.href ? "text-colorLinkText1! hover:text-colorLinkText2!" : "";

        return (
          <Fragment key={idx}>
            {hasChild && (
              <li className="rd-megamenu-list-item">
                <a
                  className={`rd-megamenu-list-link cursor-pointer ${hrefClass}`}
                  data-toggle="collapse"
                  data-target={`#${collapseId}`}
                  aria-controls={collapseId}
                  aria-expanded="false"
                >
                  {item.title}
                </a>
                <div className="pl-3 mt-2 space-y-2 collapse visible!" id={collapseId}>
                  {item.child.map((itemChild, itemChildIdx) => (
                    <a key={itemChildIdx} className={`rd-megamenu-list-link !pr-12 ${hrefClass}`} href={itemChild.href}>
                      - {itemChild.title}
                    </a>
                  ))}
                </div>
              </li>
            )}

            {!hasChild && (
              <li className="rd-megamenu-list-item">
                <a className={`rd-megamenu-list-link ${hrefClass}`} href={item.href}>
                  {item.title}
                </a>
              </li>
            )}
          </Fragment>
        );
      })}
    </ul>
  );
};
