"use client";

import { useGetProfile } from "@/app/[name]/(Profile)/profile/hooks/userProfileData";
import { glassSurfaceNav } from "@/lib/styles/glassSurface";
import clsx from "clsx";
import type { Icon } from "iconsax-react";
import { Bag2, Heart, Home2, InfoCircle, Reserve } from "iconsax-react";
import Link from "next/link";
import { useParams, usePathname, useRouter } from "next/navigation";
import { toastLoginRequired } from "../Toast";

type BottomNavBarProps = {
  onPagerClick?: () => void;
};

type NavItemProps = {
  href?: string;
  isActive: boolean;
  onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;
  onButtonClick?: () => void;
  Icon: Icon;
};

function NavItem({ href, isActive, onClick, onButtonClick, Icon }: NavItemProps) {
  const className = clsx("flex-1 flex items-center justify-center h-full rounded-full", isActive && "bg-primary/12");

  const icon = <Icon size={20} color="currentColor" variant={isActive ? "Bold" : "Linear"} className={isActive ? "text-primary" : "text-icon-deactive"} />;

  if (onButtonClick) {
    return (
      <button type="button" onClick={onButtonClick} className={className}>
        {icon}
      </button>
    );
  }

  return (
    <Link href={href ?? "#"} onClick={onClick} className={className}>
      {icon}
    </Link>
  );
}

function BottomNavBar({ onPagerClick }: BottomNavBarProps) {
  const params = useParams();
  const name = params.name as string;
  const pathname = usePathname();
  const router = useRouter();
  const { isSuccess } = useGetProfile();

  const isHomeActive = pathname === `/${name}`;
  const isFavoriteActive = pathname.startsWith(`/${name}/favorite`);
  const isPagerActive = pathname.includes("/pager");
  const isAboutActive = pathname.startsWith(`/${name}/about`);
  const isCartActive = pathname.startsWith(`/${name}/cart`);

  const handleFavoritesClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    e.preventDefault();
    if (isSuccess) {
      router.push(`/${name}/favorite`);
    } else {
      e.stopPropagation();
      toastLoginRequired(() => router.push(`/${name}/auth`), "error");
    }
  };

  return (
    <div className={glassSurfaceNav("mx-auto w-full rounded-full flex items-center h-14 max-w-md gap-2.5")}>
      <NavItem href={`/${name}`} isActive={isHomeActive} Icon={Home2} />
      <NavItem href={`/${name}/favorite`} isActive={isFavoriteActive} onClick={handleFavoritesClick} Icon={Heart} />
      {onPagerClick ? <NavItem isActive={isPagerActive} onButtonClick={onPagerClick} Icon={Reserve} /> : <NavItem href={`/${name}/pager`} isActive={isPagerActive} Icon={Reserve} />}
      <NavItem href={`/${name}/about`} isActive={isAboutActive} Icon={InfoCircle} />
      <NavItem href={`/${name}/cart`} isActive={isCartActive} Icon={Bag2} />
    </div>
  );
}

export default BottomNavBar;
