import { ArrowDown2 } from "iconsax-react";
import { FC, ReactNode, useEffect, useState } from "react";
import { clx } from "../../helpers/utils";
import { canAccessMenuItem } from "../../helpers/permissions";
import { useGetAdminPermissions } from "../../pages/users/hooks/useUserData";

type Props = {
  title: string;
  isActive: boolean;
  activeName?: string;
  activeNames?: readonly string[];
  children: ReactNode;
};

const SubMenuAccordion: FC<Props> = ({ title, isActive, activeName, activeNames, children }) => {
  const { data: adminPermissions } = useGetAdminPermissions();
  const [open, setOpen] = useState(isActive);

  useEffect(() => {
    if (isActive) {
      setOpen(true);
    }
  }, [isActive]);

  if (!canAccessMenuItem(adminPermissions?.data?.permissions, activeName, activeNames)) {
    return null;
  }

  return (
    <div>
      <button
        type="button"
        onClick={() => setOpen((prev) => !prev)}
        className="flex text-xs gap-6 mt-1 w-full cursor-pointer"
      >
        <div className={clx("w-1 bg-black h-6", !isActive && "invisible")} />
        <div className="flex gap-2 items-center flex-1 justify-between mt-1 pl-4">
          <div className={isActive ? "text-black" : "text-description"}>{title}</div>
          <div className={clx("transition-all", !open && "rotate-180")}>
            <ArrowDown2
              size={14}
              color="#c3c7dd"
            />
          </div>
        </div>
      </button>
      {open && <div className="flex flex-col gap-2 mr-3 mt-2">{children}</div>}
    </div>
  );
};

export default SubMenuAccordion;
