import { useCallback, useMemo } from "react";
import { useParams } from "next/navigation";
import { useGetProfile } from "@/app/[name]/(Profile)/profile/hooks/userProfileData";
import { useReceiptStore } from "@/zustand/receiptStore";
import {
  useBulkCart,
  useClearCart,
  useDecrementCart,
  useGetCartItems,
  useIncrementCart,
} from "../hooks/useCartData";
import { toast } from "@/components/Toast";
import { extractErrorMessage } from "@/lib/func";

export const useCart = () => {
  const { isSuccess } = useGetProfile();
  const params = useParams();
  const currentSlug = (params.name as string) || null;
  const {
    clear,
    increment,
    decrement,
    setQuantity,
    items,
    slug,
    setSlug,
  } = useReceiptStore();
  const {
    mutate: mutateIncrementCart,
    isPending: isIncrementPending,
  } = useIncrementCart();
  const {
    mutate: mutateDecrementCart,
    isPending: isDecrementPending,
  } = useDecrementCart();
  const { mutate: mutateClearCart } = useClearCart();
  const {
    mutate: mutateBulkCart,
    isPending: isBulkPending,
  } = useBulkCart();
  const { data: cartItems } = useGetCartItems(isSuccess);

  const addToCart = (id: string | number) => {
    if (isSuccess) {
      mutateIncrementCart(id, {
        onError: (error) => {
          toast(extractErrorMessage(error), "error");
        },
      });
    } else {
      // تنظیم slug هنگام افزودن آیتم به سبد (فقط برای کاربران لاگین نشده)
      if (currentSlug && slug !== currentSlug) {
        setSlug(currentSlug);
      }
      increment(id);
    }
  };

  const removeFromCart = (id: string | number) => {
    if (isSuccess) {
      mutateDecrementCart(id, {
        onError: (error) => {
          toast(extractErrorMessage(error), "error");
        },
      });
    } else {
      decrement(id);
    }
  };

  const setCartQuantity = (id: string | number, quantity: number) => {
    if (isSuccess) {
      mutateBulkCart(
        { items: [{ variantId: String(id), quantity }] },
        {
          onError: (error) => {
            toast(extractErrorMessage(error), "error");
          },
        }
      );
    } else {
      if (currentSlug && slug !== currentSlug) {
        setSlug(currentSlug);
      }
      setQuantity(id, quantity);
    }
  };

  const clearCart = useCallback(() => {
    if (isSuccess) {
      mutateClearCart(undefined, {
        onError: (error) => {
          toast(extractErrorMessage(error), "error");
        },
      });
    } else {
      clear();
    }
  }, [isSuccess, mutateClearCart, clear]);

  const cartItemsMap = useMemo(() => {
    if (isSuccess) {
      if (!cartItems?.data?.items) {
        return {};
      }
      return cartItems.data.items.reduce((acc, item) => {
        acc[item.variantId] = {
          quantity: item.quantity,
          ...(item.variantValue != null && { variantValue: item.variantValue }),
          ...(item.image != null && { image: item.image }),
        };
        return acc;
      }, {} as Record<string | number, { quantity: number; variantValue?: string; image?: string }>);
    } else {
      return items;
    }
  }, [isSuccess, cartItems?.data?.items, items]);

  const isCartMutating = isIncrementPending || isDecrementPending || isBulkPending;

  // برای کاربران لاگین شده، slug از API می‌آید (در cartItems.data.shopId)
  // برای کاربران لاگین نشده، slug از receiptStore می‌آید
  const cartSlug = useMemo(() => {
    if (isSuccess && cartItems?.data?.shopId) {
      return currentSlug;
    }
    return slug;
  }, [isSuccess, cartItems?.data?.shopId, currentSlug, slug]);

  return {
    items: cartItemsMap,
    slug: cartSlug,
    increment,
    decrement,
    clear,
    addToCart,
    removeFromCart,
    setCartQuantity,
    clearCart,
    isCartMutating,
  };
};
