"use client";

import { IconButton, List, Typography } from "@material-tailwind/react";
import { usePathname } from "next/navigation";
import { useMemo } from "react";
import { BsBoxSeam, BsCart2 } from "react-icons/bs";
import { FiHeadphones } from "react-icons/fi";
import { HiOutlineUser } from "react-icons/hi";
import { IoDocumentTextOutline } from "react-icons/io5";
import { IoClose } from "react-icons/io5";
import { LiaWalletSolid } from "react-icons/lia";
import { MdContentCopy, MdOutlineLogout } from "react-icons/md";
import { TbHistory } from "react-icons/tb";
import { toast } from "react-toastify";

import { KYC_STATUS } from "../constants/app";
import { FeatureCodes } from "../constants/feature-flags";
import { ROUTES } from "../constants/routes";
import { useMainContext } from "../contexts/MainWrapperContext";
import useCopy from "../hooks/useCopy";
import useCustomRouter from "../hooks/useCustomRouter";
import useOnlineUser from "../hooks/useOnlineUser";
import { _useScopedI18n } from "../i18n/client";
import { useLoadingStore } from "../stores/loadingStore";
import { useUserStore } from "../stores/userStore";
import ButtonCustom from "./Button";
import { BrandIcon } from "./icons/BrandIcon";
import ListItemComponent from "./ListItemComponent";
import ServerTime from "./ServerTime";

export type SidebarProps = {
  bidNumber: string;
  onClose: () => void;
  handleLogout: () => void;
  cartProductsCount: number;
};

export default function Sidebar({
  bidNumber,
  onClose,
  handleLogout,
  cartProductsCount,
}: SidebarProps) {
  //
  const { handleCopy } = useCopy();
  const { getAletaAuth } = useOnlineUser();
  const { push } = useCustomRouter();
  const { setLoading: setAppLoading } = useLoadingStore();
  const { user } = useUserStore();

  const pathname = usePathname();

  const scopeT = _useScopedI18n("sideBarMenu");

  const { featureFlags } = useMainContext();

  const MENU_ITEMS = useMemo(() => {
    //
    const iconClassName = `h-5 w-5`;

    return {
      primary: [
        {
          icon: <BsBoxSeam className={iconClassName} />,
          title: scopeT("products"),
          href: ROUTES.dashboard.products,
          badge: null,
          active: pathname.startsWith(ROUTES.dashboard.products),
          enable: true,
          customActionEnable: false,
          customAction: () => {},
        },
        {
          icon: <BsCart2 className={iconClassName} />,
          title: scopeT("myCart"),
          href: ROUTES.dashboard.cart,
          // badge: cartQty > 0 ? cartQty : null,
          badge: cartProductsCount,
          active:
            pathname.startsWith(ROUTES.dashboard.cart) ||
            pathname.startsWith(ROUTES.dashboard.checkout) ||
            pathname.startsWith(ROUTES.dashboard.payment) ||
            pathname.startsWith(ROUTES.dashboard.payment),
          enable: true,
          customActionEnable: false,
          customAction: () => {},
        },
        {
          icon: <TbHistory className={iconClassName} />,
          title: scopeT("orderHistory"),
          href: ROUTES.dashboard.orders,
          badge: null,
          active: pathname.startsWith(ROUTES.dashboard.orders),
          enable: true,
          customActionEnable: false,
          customAction: () => {},
        },
        {
          icon: <LiaWalletSolid className={iconClassName} />,
          title: scopeT("AletaPay"),
          href: "#",
          badge:
            (user &&
              user?.pgUser?.aletaState === KYC_STATUS.SUBSCRIPTION_REQUIRED) ||
            user?.pgUser?.aletaState === KYC_STATUS.KYC_REQUIRED ? (
              <div className="text-xs">Setup Now</div>
            ) : null,
          active: pathname.startsWith("aleta"),
          enable: !featureFlags?.[FeatureCodes.ALETA_PAYMENT]
            ? false
            : featureFlags?.[FeatureCodes.ALETA_PAYMENT]?.isActive === true,
          customActionEnable: true,
          customAction: async () => {
            setAppLoading(true);
            const result = await getAletaAuth();
            if (result.isSuccess) {
              push(result.data.authUrl);
            } else {
              toast.error(
                <>
                  <span>
                    Failed to fetch aleta auth code, please try again later
                  </span>
                </>,
                {
                  position: "top-right",
                  autoClose: 2000,
                },
              );
            }
            setAppLoading(false);
          },
        },
      ],
      secondary: [
        {
          icon: <HiOutlineUser className={iconClassName} />,
          title: scopeT("profile"),
          href: ROUTES.dashboard.profile,
          badge: null,
          active: pathname.startsWith(ROUTES.dashboard.profile),
          enable: true,
        },
        {
          icon: <IoDocumentTextOutline className={iconClassName} />,
          title: scopeT("wiki"),
          href: ROUTES.dashboard.wiki,
          badge: null,
          active: false,
          target: "_blank",
          enable: true,
        },
        {
          icon: <FiHeadphones className={iconClassName} />,
          title: scopeT("support"),
          href: ROUTES.dashboard.support,
          badge: null,
          active: false,
          target: "_blank",
          enable: true,
        },
      ],
    };
  }, [
    pathname,
    cartProductsCount,
    scopeT,
    featureFlags,
    getAletaAuth,
    push,
    setAppLoading,
    user,
  ]);

  return (
    <>
      <div className="bg-white">
        <div className="md:h-[4.36rem] px-2 py-3 md:p-3 border-b border-b-slate-50 border-r-slate-50 flex justify-between lg:justify-center items-center z-50">
          <a href="/products" className="w-36 brandIcon">
            <BrandIcon width={150} height={34} />
          </a>
          <IconButton
            onClick={onClose}
            className="bg-gray-50 h-10 w-10 !max-h-10 !max-w-10 shadow-none border border-slate-50 lg:hidden"
          >
            <IoClose className="h-6 w-6 text-black-500" />
          </IconButton>
        </div>

        <div className="sidebar-body p-2">
          <div className="md:hidden mt-2">
            <ServerTime />
          </div>

          {/* <div className="py-4 px-3">
            <Typography
              variant="h6"
              className="text-xs text-gray-500 font-normal"
            >
              {scopeT("navigation")}
            </Typography>
          </div> */}
          <List className="p-0 text-gray-500 gap-0 lg:gap-1 w-full min-w-full mt-1">
            {MENU_ITEMS.primary.map(
              (
                {
                  icon,
                  title,
                  href,
                  badge,
                  active,
                  enable,
                  customAction,
                  customActionEnable,
                },
                index,
              ) =>
                enable && (
                  <ListItemComponent
                    key={index}
                    href={href}
                    prefix={icon}
                    ListItemName={title}
                    active={active}
                    cartProductsCount={badge}
                    customAction={customAction}
                    customActionEnable={customActionEnable}
                    onClick={onClose}
                  />
                ),
            )}

            <hr className="m-3 block border-slate-50" />

            {MENU_ITEMS.secondary.map(
              ({ icon, title, href, badge, active, target, enable }, index) =>
                enable && (
                  <ListItemComponent
                    key={index}
                    href={href}
                    prefix={icon}
                    ListItemName={title}
                    active={active}
                    target={target}
                    cartProductsCount={badge}
                    onClick={onClose}
                  />
                ),
            )}
          </List>

          <div className="p-3 flex justify-between items-center lg:hidden">
            <Typography
              as="span"
              variant="small"
              className="text-black-500 text-base font-medium"
            >
              Bid : {bidNumber}
            </Typography>
            <IconButton
              variant="outlined"
              className="p-0 rounded-full bg-gray-100/40 border-none"
              onClick={() => handleCopy(bidNumber)}
            >
              <MdContentCopy className="h-4 w-4" />
            </IconButton>
          </div>
          <div className="p-3 mt-5 lg:hidden">
            <ButtonCustom
              onClick={handleLogout}
              icon={<MdOutlineLogout className="h-5 w-5" />}
              className="gap-2 font-medium text-sm w-full p-3.5"
            >
              {scopeT("logout")}
            </ButtonCustom>
          </div>
        </div>
      </div>
    </>
  );
}
