import Input from "@/components/Input";
import { Paths } from "@/config/Paths";
import { clx } from "@/helpers/utils";
import { useGetBusiness } from "@/pages/business/hooks/useBusinessData";
import HeaderUserMenu from "@/shared/components/HeaderUserMenu";
import { useSharedStore } from "@/shared/store/sharedStore";
import { Eye, HambergerMenu } from "iconsax-react";
import { type FC, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Link, useLocation } from "react-router-dom";

type SidebarSize = "default" | "wide";

type HeaderProps = {
  hasMainSidebar?: boolean;
  sidebarSize?: SidebarSize;
};

const sidebarSizeClasses: Record<
  SidebarSize,
  { base: string; withSub: string }
> = {
  default: {
    base: "xl:right-[285px] xl:w-[calc(100%-305px)]",
    withSub: "xl:right-[320px] xl:w-[calc(100%-340px)]",
  },
  wide: {
    base: "xl:right-[390px] xl:w-[calc(100%-406px)]",
    withSub: "xl:right-[425px] xl:w-[calc(100%-441px)]",
  },
};

const Header: FC<HeaderProps> = ({
  hasMainSidebar = true,
  sidebarSize = "default",
}) => {
  const { t } = useTranslation("global");
  const {
    setOpenSidebar,
    openSidebar,
    hasSubMenu,
    setSearch,
    editorCatalogSlug,
  } = useSharedStore();

  const { data: business } = useGetBusiness();
  const location = useLocation();
  const editorPathPrefix = `${Paths.editor}/`;
  const isEditorRoute =
    location.pathname.startsWith(editorPathPrefix) &&
    location.pathname.length > editorPathPrefix.length;
  const viewerSlug = isEditorRoute ? (editorCatalogSlug ?? "") : "";

  useEffect(() => {
    setSearch("");
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location.pathname]);

  return (
    <div
      className={clx(
        "fixed z-10 right-4 left-4 top-4 xl:h-16 h-12 flex items-center px-6 bg-white justify-between rounded-[32px]",
        hasMainSidebar &&
          (hasSubMenu
            ? sidebarSizeClasses[sidebarSize].withSub
            : sidebarSizeClasses[sidebarSize].base),
      )}
    >
      <div className="min-w-[270px] hidden xl:block">
        <Input
          variant="search"
          placeholder={t("header.search")}
          onChangeSearchFinal={(value) => setSearch(value)}
        />
      </div>

      <button
        type="button"
        onClick={() => setOpenSidebar(!openSidebar)}
        className="xl:hidden block"
      >
        <HambergerMenu size={24} color="black" />
      </button>

      <div className="flex xl:gap-6 gap-4 items-center">
        {isEditorRoute && viewerSlug ? (
          <Link
            target="_blank"
            to={`${Paths.viewerBySlug}/${business?.data?.slug}/${viewerSlug}`}
            className="flex items-center"
            aria-label={t("header.open_viewer")}
            title={t("header.open_viewer")}
          >
            <Eye size={20} color="black" />
          </Link>
        ) : null}

        <HeaderUserMenu />
      </div>
    </div>
  );
};

export default Header;
