import hocAuth from "@/hocs/auth";
import { CommonComponent } from "@/types/typings";
import { CustomTabBar, Icon, IconNames } from "@/components";
import { useEffect, useState } from "react";
import { auth } from "@/services";
import { Text, View } from "@tarojs/components";
import Taro from "@tarojs/taro";

export default hocAuth(function Page(props: CommonComponent) {
  const { userRoleVO } = props;

  const [menuList, setMenuList] = useState<any[]>();

  const initMenuList = async (roleIdList: string[]) => {
    const {
      data: { data: menuTree },
    } = await auth.user.userMenu({
      roleMenuTreeQry: {
        //@ts-ignore
        roleId: roleIdList,
        platformId: "1991353387274342401",
      },
    });
    setMenuList(menuTree);
  };

  useEffect(() => {
    initMenuList([userRoleVO.roleId]).then();
  }, [userRoleVO.roleId]);

  const handleMenuClick = (menu: BusinessAPI.MenuVO) => {
    if (menu.path) {
      Taro.navigateTo({
        url: menu.path,
      });
    }
  };

  const renderMenuTree = (
    menus: BusinessAPI.MenuVO[] | undefined,
    level = 0,
  ) => {
    if (!menus || menus.length === 0) return null;

    if (level === 1) {
      return (
        <View className="grid grid-cols-4">
          {menus.map((menu) => (
            <View
              key={menu.menuId}
              className="rounded-xl bg-white text-center"
              onClick={() => handleMenuClick(menu)}
            >
              <View
                className={`icon-container m-2 mx-auto flex h-10 w-10 items-center justify-center rounded-lg`}
                style={{ backgroundColor: `rgb(${menu.bgColorClass})` }}
              >
                <Icon
                  name={menu.icon?.replace("icon-", "") as IconNames}
                  color={`rgb(${menu.iconColor})`}
                />
              </View>
              <View className={`text-xs text-gray-700`}>{menu.name}</View>
            </View>
          ))}
        </View>
      );
    }

    return (
      <View className={"flex flex-col gap-2.5"}>
        {menus.map((menu) => (
          <View
            key={menu.menuId}
            className={`flex flex-col gap-2.5 level-${level}`}
          >
            <View className="">
              <Text className="menu-name">{menu.name}</Text>
            </View>
            {menu.routes && menu.routes.length > 0 && (
              <View className="rounded-md bg-white p-2.5 shadow-md">
                {renderMenuTree(menu.routes as BusinessAPI.MenuVO[], level + 1)}
              </View>
            )}
          </View>
        ))}
      </View>
    );
  };

  return (
    <>
      <View className="p-2.5">{renderMenuTree(menuList)}</View>
      {process.env.TARO_ENV === "weapp" && <CustomTabBar />}
    </>
  );
});
