"use client";
import { useRouter } from "next/navigation";
import { useMemo } from "react";
import type React from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { useCart, useFavorites, useOrders, useCartCount } from "@/lib/hooks";
import { Skeleton } from "@/components/ui/skeleton";
import { useTranslations } from "next-intl";
import { useLogout } from "@/lib/hooks/useAuth";
import { CartIcon, FavoriteIcon, OrderIcon } from "@/components/icons";

interface ActionButtonsProps {
  isAuthenticated: boolean;
  onAuthClick: () => void;
  isLoading?: boolean;
  locale?: string;
}

interface ActionButtonData {
  icon: React.ReactNode;
  label: string;
  href?: string;
  onClick?: () => void;
  badgeCount?: number;
  isLoading?: boolean;
}

export default function ActionButtons({
  isAuthenticated,
  onAuthClick,
  isLoading: authLoading,
  locale = "ru",
}: ActionButtonsProps) {
  const t = useTranslations();
  const { mutate: logout, isPending: isLoggingOut } = useLogout();
  const router = useRouter();
  const { data: cartData, isLoading: cartLoading } = useCart();
  const { data: favoritesData, isLoading: favoritesLoading } = useFavorites();
  const { data: ordersData, isLoading: ordersLoading } = useOrders();

  const cartCount = useCartCount();

  const favoritesCount = useMemo(() => {
    if (!favoritesData) return 0;
    return Array.isArray(favoritesData) ? favoritesData.length : 0;
  }, [favoritesData]);

  const ordersCount = useMemo(() => {
    if (!ordersData) return 0;
    return Array.isArray(ordersData) ? ordersData.length : 0;
  }, [ordersData]);

  const handleLogout = () => {
    logout(undefined, {
      onSuccess: () => {
        router.push(`/${locale}`);
        router.refresh();
      },
    });
  };

  const buttons: ActionButtonData[] = useMemo(
    () => [
      {
        icon: <OrderIcon />,
        label: t("common.orders"),
        href: "/orders",
        badgeCount: ordersCount,
        isLoading: ordersLoading,
      },
      {
        icon: <FavoriteIcon />,
        label: t("common.favorites"),
        href: "/favorites",
        badgeCount: favoritesCount,
        isLoading: favoritesLoading,
      },
      {
        icon: <CartIcon />,
        label: t("common.cart"),
        href: "/cart",
        badgeCount: cartCount,
        isLoading: cartLoading,
      },
    ],
    [
      ordersCount,
      ordersLoading,
      favoritesCount,
      favoritesLoading,
      cartCount,
      cartLoading,
      t,
    ],
  );

  return (
    <div className="hidden items-center gap-1 lg:flex">
      {buttons.map((button, index) => (
        <ActionButton key={index} {...button} />
      ))}
    </div>
  );
}

function ActionButton({
  icon,
  label,
  href,
  onClick,
  badgeCount,
  isLoading,
}: ActionButtonData) {
  const buttonContent = (
    <Button
      variant="ghost"
      size="sm"
      className="relative cursor-pointer flex-col gap-1 h-auto px-3 py-2.5  hover:bg-gray-100 transition-all duration-200 group"
      onClick={onClick}
    >
      <div className="relative">
        <div className="transition-transform duration-200 group-hover:scale-110">
          {icon}
        </div>
        {badgeCount !== undefined && badgeCount > 0 && (
          <Badge className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px] font-normal bg-gray-900 hover:bg-gray-900 text-white border border-white shadow-sm">
            {isLoading ? (
              <Skeleton className="h-3 w-3 " />
            ) : badgeCount > 99 ? (
              "99+"
            ) : (
              badgeCount
            )}
          </Badge>
        )}
      </div>
      <span className="text-xs  text-gray-700 group-hover:text-gray-900 transition-colors">
        {label}
      </span>
    </Button>
  );

  if (href) {
    return <Link href={href}>{buttonContent}</Link>;
  }

  return buttonContent;
}
