// user store
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";

import { CATEGORY_FOR_SMART_PAY } from "../constants/app";
import { ICart, UserAddress } from "../types/cart";

interface ICommissionEligibilityFound {
  status: boolean;
  data?: Array<string>;
}

export type StoreType = {
  cart: ICart | null;
  cartQty: number;
  haveSmartPay?: boolean;
  loading: boolean;
  userBillingAddress: UserAddress[];
  userShippingAddress: UserAddress[];
  commissionNonEligibleFound: ICommissionEligibilityFound;
  paymentMethods: any;
  setPaymentMethods: (methods: any) => void;
  setUserBillingAddress: (address: UserAddress[]) => void;
  setUserShippingAddress: (address: UserAddress[]) => void;
  setCart: (cartData: ICart | null) => void;
  setLoading: (newLoading: boolean) => void;
  refechCart?: () => void | null;
  setRefechCart: (fn: () => void) => void;
};

const checkSmartPayCategory = (cartProducts: any[]): boolean => {
  return cartProducts?.some(
    (item) => item.product?.category?.code === CATEGORY_FOR_SMART_PAY,
  );
};

const getTotalProductQuantity = (cartProducts: any[]): number => {
  if (!cartProducts || cartProducts?.length === 0) return 0;
  let totalQuantity = 0;
  cartProducts.forEach((item) => {
    const itemQuantity = Number(item.quantity);
    if (!isNaN(itemQuantity)) {
      totalQuantity += itemQuantity;
    }
  });
  return totalQuantity;
};

const checkNonEligibleProductForCommission = (
  cartProducts: any[],
): ICommissionEligibilityFound => {
  let status = false;
  let data = [];

  if (cartProducts) {
    cartProducts.forEach((item) => {
      if (item.isEligibleForCommission === false) {
        status = true;
        data.push(`${item.product.category.name}`);
      }
    });
  }

  return {
    status,
    data,
  };
};

export const useCartStore = create<StoreType>()(
  persist(
    (set, get) => ({
      cart: get()?.cart ?? null, // Initial state for cart info
      cartQty: get()?.cartQty ?? 0,
      loading: true, // Tracks if cart data is loading
      userBillingAddress: get()?.userBillingAddress ?? null,
      userShippingAddress: get()?.userShippingAddress ?? null,
      commissionNonEligibleFound: get()?.commissionNonEligibleFound ?? {
        status: false,
      },
      refechCart: undefined,
      paymentMethods: get()?.paymentMethods ?? null,
      setCart: (data: ICart | null) =>
        set({
          cart: data,
          haveSmartPay: data
            ? checkSmartPayCategory(data?.cartProducts)
            : false,
          cartQty: data ? getTotalProductQuantity(data?.cartProducts) : 0,
          commissionNonEligibleFound: checkNonEligibleProductForCommission(
            data?.cartProducts,
          ),
          loading: false,
        }), // Action to update
      setLoading: (state: boolean) => set({ loading: state }), // Action to update loading state
      setUserBillingAddress: (address: UserAddress[]) =>
        set({ userBillingAddress: address }),
      setUserShippingAddress: (address: UserAddress[]) =>
        set({ userShippingAddress: address }),
      setRefechCart: (fn: () => void) => set({ refechCart: fn }),
      setPaymentMethods: (methods: any) => set({ paymentMethods: methods }),
    }),
    {
      name: "cartStore",
      storage: createJSONStorage(() => localStorage),
    },
  ),
);
