import { removeRefreshToken, removeToken } from "@/config/func";
import { Paths } from "@/config/Paths";
import { useAuth } from "@/context/AuthContext";
import { useGetBusiness } from "@/pages/business/hooks/useBusinessData";
import { getAdminFullName, type BusinessType } from "@/pages/business/types/Types";
import { Popover, PopoverButton, PopoverPanel } from "@headlessui/react";
import { ArrowDown2, CloseCircle, DocumentText, Logout } from "iconsax-react";
import { useEffect, useState, type FC } from "react";
import { useTranslation } from "react-i18next";
import { Link, useLocation } from "react-router-dom";

type BusinessLogoProps = {
  business: BusinessType;
  size?: "sm" | "lg";
};

const BusinessLogo: FC<BusinessLogoProps> = ({ business, size = "sm" }) => {
  const initial = business.name.trim().charAt(0).toUpperCase();
  const sizeClass = size === "lg" ? "size-14 text-xl" : "size-6 text-[11px]";

  if (business.logoUrl) {
    return (
      <div className={`${sizeClass} rounded-full overflow-hidden bg-description`}>
        <img src={business.logoUrl} className="size-full object-cover" alt="" />
      </div>
    );
  }

  return <div className={`${sizeClass} rounded-full pt-[2px] bg-secondary flex items-center justify-center font-medium text-desc leading-none select-none`}>{initial}</div>;
};

const HeaderUserMenu: FC = () => {
  const [popoverKey, setPopoverKey] = useState(0);
  const location = useLocation();
  const { t } = useTranslation("global");
  const { data: businessResponse } = useGetBusiness();
  const { refreshAuth } = useAuth();

  const business = businessResponse?.data;
  const admin = business?.admin;
  const adminName = getAdminFullName(admin);

  const closePopover = () => setPopoverKey((key) => key + 1);

  useEffect(() => {
    setPopoverKey((key) => key + 1);
  }, [location.pathname]);

  if (!business) return null;

  const handleLogout = () => {
    removeToken();
    removeRefreshToken();
    refreshAuth();
    window.location.href = Paths.home;
  };

  return (
    <Popover className="relative" key={popoverKey}>
      <PopoverButton className="flex items-center gap-2 outline-none">
        <BusinessLogo business={business} />
        <div className="hidden sm:flex items-center gap-1">
          <span className="text-xs">{adminName}</span>
          <ArrowDown2 size={14} color="#8C90A3" />
        </div>
      </PopoverButton>

      <PopoverPanel
        style={{
          minHeight: window.innerWidth < 1140 ? window.innerHeight : undefined,
        }}
        anchor="bottom"
        className="flex xl:ml-6 overflow-auto flex-col gap-3 bg-white boxShadow xl:mt-7 z-30 py-4 text-xs rounded-2.5 xl:w-[300px] -mt-[50px] w-full fixed xl:h-fit h-full shadow-md"
      >
        <button type="button" className="absolute xl:hidden top-6 left-6" onClick={closePopover}>
          <CloseCircle size={20} color="#da2129" />
        </button>

        <Link to={`${Paths.catalog.business}${business.slug}`} onClick={closePopover} className="flex flex-col gap-2 items-center justify-center border-b border-[#EAEDF5] pb-4">
          <BusinessLogo business={business} size="lg" />
          <div>{adminName}</div>
          <div className="text-description">{business.name}</div>
          {admin?.phone ? <div className="text-description">{admin.phone}</div> : null}
        </Link>

        <div className="px-6 mt-2">
          <Link to={Paths.catalog.list} onClick={closePopover} className="flex gap-2 items-center cursor-pointer">
            <DocumentText size={20} color="black" />
            <span>{t("sidebar.catalog")}</span>
          </Link>
        </div>
        <div className="px-6 mt-2">
          <button type="button" onClick={handleLogout} className="flex gap-2 items-center cursor-pointer">
            <Logout size={20} color="#da2129" />
            <span>{t("sidebar.logout")}</span>
          </button>
        </div>
      </PopoverPanel>
    </Popover>
  );
};

export default HeaderUserMenu;
