import {
  Box,
  Category,
  DocumentLike,
  Headphone,
  Home,
  Logout,
  Money3,
  Profile,
  Profile2User,
  Setting2,
  TickSquare,
  UserOctagon,
  UserTick,
} from "iconsax-react";
import { FC, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useLocation } from "react-router-dom";
import LogoSmall from "../assets/images/logo-small.svg";
import LogoImage from "../assets/images/logo.svg";
import { Pages } from "../config/Pages";
import { getSubMenuNameFromPath } from "../config/SideBarSubMenu";
import {
  CONTENT_PERMISSION_RESOURCES,
  FINANCIAL_PERMISSION_RESOURCES,
  hasAnyPermission,
  hasPermission,
  PRODUCT_PERMISSION_RESOURCES,
  SUPPORT_PERMISSION_RESOURCES,
  TASK_MANAGER_PERMISSION_RESOURCES,
  USERS_SIDEBAR_PERMISSION_RESOURCES,
} from "../helpers/permissions";
import { clx } from "../helpers/utils";
import { useGetProfile } from "../pages/profile/hooks/useProfileData";
import { useGetAdminPermissions } from "../pages/users/hooks/useUserData";
import ContentSubMenu from "./components/ContentSubMenu";
import CustomersSubMenu from "./components/CustomersSubMenu";
import FinancialSubMenu from "./components/FinancialSubMenu";
import OtherSubMenu from "./components/OtherSubMenu";
import ProductsSubMenu from "./components/ProductsSubMenu";
import ResellerSubMenu from "./components/ResellerSubMenu";
import ServicesSubMenu from "./components/ServicesSubMenu";
import SupportSubMenu from "./components/SupportSubMenu";
import TaskManagerSubMenu from "./components/TaskManagerSubMenu";
import UsersSubMenu from "./components/UsersSubMenu";
import SideBarItem from "./SideBarItem";
import { useSharedStore } from "./store/sharedStore";

const SideBar: FC = () => {
  const { t } = useTranslation("global");
  const { openSidebar, setOpenSidebar, hasSubMenu, setSubMenuName, setSubtMenu, subMenuName } = useSharedStore();
  const location = useLocation();
  const { data: profile } = useGetProfile();
  const { data: adminPermissions } = useGetAdminPermissions();

  const isGroupActive = (name: string) => subMenuName === name || getSubMenuNameFromPath(location.pathname) === name;
  const isPathActive = (name: string) => location.pathname.includes(name);

  const permissions = adminPermissions?.data?.permissions;

  const hasProductPermission = hasAnyPermission(permissions, PRODUCT_PERMISSION_RESOURCES);
  const hasTaskManagerPermission = hasAnyPermission(permissions, TASK_MANAGER_PERMISSION_RESOURCES);

  const productsDefaultLink = (() => {
    const permissionNames = permissions?.map((p: { name: string }) => p.name) ?? [];
    if (permissionNames.includes("dmenu")) return Pages.dmenu.icons.list;
    if (permissionNames.includes("dkala")) return Pages.dkala.icons.list;
    if (permissionNames.includes("dmail")) return Pages.dmail.list;
    if (permissionNames.includes("dpage")) return Pages.dpage.stickers.list;
    return Pages.dashboard;
  })();

  const usersDefaultLink = Pages.users.list;

  useEffect(() => {
    const groupName = getSubMenuNameFromPath(location.pathname);

    if (groupName) {
      setSubMenuName(groupName);
      setSubtMenu(true);
    } else {
      setSubMenuName("");
      setSubtMenu(false);
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location.pathname]);

  const iconSizeSideBar = 20;

  return (
    <>
      {openSidebar && (
        <div
          className="fixed top-0 left-0 right-0 bottom-0 bg-black bg-opacity-50 z-10"
          onClick={() => setOpenSidebar(false)}
        />
      )}
      <div
        className={clx(
          "fixed xl:flex translate-x-[400px] xl:translate-x-0 transition-all ease-in-out opacity-0 invisible xl:visible xl:opacity-100  xl:right-4 right-0 xl:top-4 top-0 xl:bottom-4 bottom-0 xl:rounded-[32px] w-[250px] bg-white flex-col py-12",
          openSidebar && "opacity-100 visible -translate-x-[0px] block z-40",
          hasSubMenu && "w-24 !rounded-tl-none !rounded-bl-none",
        )}
      >
        <div className="flex justify-center">
          {!hasSubMenu ? (
            <img
              src={LogoImage}
              className="w-[140px]"
            />
          ) : (
            <img
              src={LogoSmall}
              className="w-7"
            />
          )}
        </div>

        <div className="flex-1 flex flex-col h-full overflow-y-auto no-scrollbar">
          <div className="text-xs text-[#8C90A3] mt-6">
            <SideBarItem
              icon={
                <Home
                  variant={isPathActive("dashboard") ? "Bold" : "Outline"}
                  color={isPathActive("dashboard") ? "black" : "#8C90A3"}
                  size={iconSizeSideBar}
                />
              }
              title={t("sidebar.mainpage")}
              isActive={isPathActive("dashboard")}
              link={Pages.dashboard}
              activeName=""
            />

            <SideBarItem
              icon={
                <Category
                  variant={isGroupActive("services") ? "Bold" : "Outline"}
                  color={isGroupActive("services") ? "black" : "#8C90A3"}
                  size={iconSizeSideBar}
                />
              }
              title={t("sidebar.services")}
              isActive={isGroupActive("services")}
              link={Pages.services.list}
              name="services"
              activeName="services"
            />

            <SideBarItem
              icon={
                <Profile2User
                  variant={isGroupActive("customers") ? "Bold" : "Outline"}
                  color={isGroupActive("customers") ? "black" : "#8C90A3"}
                  size={iconSizeSideBar}
                />
              }
              title={t("sidebar.customers")}
              isActive={isGroupActive("customers")}
              link={Pages.customer.list}
              name="customers"
              activeName="customers"
            />

            {hasPermission(permissions, "reseller") && (
              <SideBarItem
                icon={
                  <UserTick
                    variant={isGroupActive("representatives") ? "Bold" : "Outline"}
                    color={isGroupActive("representatives") ? "black" : "#8C90A3"}
                    size={iconSizeSideBar}
                  />
                }
                title={t("sidebar.representatives")}
                isActive={isGroupActive("representatives")}
                link={Pages.reseller.list}
                name="representatives"
                activeName="reseller"
              />
            )}

            <SideBarItem
              icon={
                <UserOctagon
                  variant={isPathActive("developers") ? "Bold" : "Outline"}
                  color={isPathActive("developers") ? "black" : "#8C90A3"}
                  size={iconSizeSideBar}
                />
              }
              title={t("sidebar.developers")}
              isActive={isPathActive("developers")}
              link={Pages.developers.list}
              activeName="developers"
            />

            <SideBarItem
              icon={
                <Profile
                  variant={isGroupActive("users") ? "Bold" : "Outline"}
                  color={isGroupActive("users") ? "black" : "#8C90A3"}
                  size={iconSizeSideBar}
                />
              }
              title={t("sidebar.users")}
              isActive={isGroupActive("users")}
              link={usersDefaultLink}
              name="users"
              activeNames={USERS_SIDEBAR_PERMISSION_RESOURCES}
            />

            {hasTaskManagerPermission && (
              <SideBarItem
                icon={
                  <TickSquare
                    variant={isGroupActive("taskmanager") ? "Bold" : "Outline"}
                    color={isGroupActive("taskmanager") ? "black" : "#8C90A3"}
                    size={iconSizeSideBar}
                  />
                }
                title={t("sidebar.taskmanager")}
                isActive={isGroupActive("taskmanager")}
                link={Pages.taskmanager.workspaceList}
                name="taskmanager"
                activeNames={TASK_MANAGER_PERMISSION_RESOURCES}
              />
            )}

            <SideBarItem
              icon={
                <DocumentLike
                  variant={isGroupActive("content") ? "Bold" : "Outline"}
                  color={isGroupActive("content") ? "black" : "#8C90A3"}
                  size={iconSizeSideBar}
                />
              }
              title={t("sidebar.mnage_content")}
              isActive={isGroupActive("content")}
              link={Pages.blog.list}
              name="content"
              activeNames={CONTENT_PERMISSION_RESOURCES}
            />

            <SideBarItem
              icon={
                <Money3
                  variant={isGroupActive("financial") ? "Bold" : "Outline"}
                  color={isGroupActive("financial") ? "black" : "#8C90A3"}
                  size={iconSizeSideBar}
                />
              }
              title={t("sidebar.financial")}
              isActive={isGroupActive("financial")}
              link={Pages.payment.list}
              name="financial"
              activeNames={FINANCIAL_PERMISSION_RESOURCES}
            />

            <SideBarItem
              icon={
                <Headphone
                  variant={isGroupActive("support") ? "Bold" : "Outline"}
                  color={isGroupActive("support") ? "black" : "#8C90A3"}
                  size={iconSizeSideBar}
                />
              }
              title={t("sidebar.support_section")}
              isActive={isGroupActive("support")}
              link={Pages.support.list}
              name="support"
              activeNames={SUPPORT_PERMISSION_RESOURCES}
            />

            {profile?.data?.user?.roles?.some((role: { name: string }) => role.name === "super_admin") && (
              <SideBarItem
                icon={
                  <Category
                    variant={isGroupActive("other") ? "Bold" : "Outline"}
                    color={isGroupActive("other") ? "black" : "#8C90A3"}
                    size={iconSizeSideBar}
                  />
                }
                title={t("sidebar.other")}
                isActive={isGroupActive("other")}
                link={Pages.feedback.list}
                name="other"
                activeName=""
              />
            )}

            {hasProductPermission && (
              <SideBarItem
                icon={
                  <Box
                    variant={isGroupActive("products") ? "Bold" : "Outline"}
                    color={isGroupActive("products") ? "black" : "#8C90A3"}
                    size={iconSizeSideBar}
                  />
                }
                title={t("sidebar.products")}
                isActive={isGroupActive("products")}
                link={productsDefaultLink}
                name="products"
                activeName=""
              />
            )}
          </div>

          <div className="flex-1 flex flex-col justify-end mt-14">
            <div className="text-xs text-[#8C90A3]">
              <SideBarItem
                icon={
                  <Setting2
                    variant={location.pathname.includes("setting") ? "Bold" : "Outline"}
                    color={location.pathname.includes("setting") ? "black" : "#8C90A3"}
                    size={iconSizeSideBar}
                  />
                }
                title={t("sidebar.setting")}
                isActive={location.pathname.includes("setting")}
                link={Pages.setting}
                activeName="settings"
              />
            </div>
            <div className="text-xs text-[#8C90A3]">
              <SideBarItem
                icon={
                  <Logout
                    variant="Outline"
                    color="#8C90A3"
                    size={iconSizeSideBar}
                  />
                }
                title={t("sidebar.logout")}
                isActive={false}
                link={`#`}
                isLogout
                activeName=""
              />
            </div>
          </div>
        </div>
      </div>

      {hasSubMenu && (openSidebar || window.innerWidth > 1139) && (
        <div className="fixed  xl:right-[112px] right-[96px] bg-white z-20 xl:top-4 xl:bottom-4 top-0 bottom-0 rounded-tl-[32px] rounded-bl-[32px] w-[190px] border-r overflow-y-auto no-scrollbar">
          {subMenuName === "services" ? (
            <ServicesSubMenu />
          ) : subMenuName === "customers" ? (
            <CustomersSubMenu />
          ) : subMenuName === "representatives" ? (
            <ResellerSubMenu />
          ) : subMenuName === "users" ? (
            <UsersSubMenu />
          ) : subMenuName === "taskmanager" ? (
            <TaskManagerSubMenu />
          ) : subMenuName === "content" ? (
            <ContentSubMenu />
          ) : subMenuName === "financial" ? (
            <FinancialSubMenu />
          ) : subMenuName === "support" ? (
            <SupportSubMenu />
          ) : subMenuName === "other" ? (
            <OtherSubMenu />
          ) : subMenuName === "products" ? (
            <ProductsSubMenu />
          ) : null}
        </div>
      )}
    </>
  );
};

export default SideBar;
