import { createSlice } from "@reduxjs/toolkit";
import { createSelector } from "@reduxjs/toolkit";
import { createNotification } from "@/customHook/useNotification";
import { customerApi } from "@/api/api";

const initialState = {
  products: [],
  wishlistLoader: true,
};
const wishlistStore = createSlice({
  name: "wishlistStoreActions",
  initialState: initialState,
  reducers: {
    addWishList(state, action) {
      if (state.products.length > 0) {
        for (const item of state.products) {
          if (item.id == action.payload.product.id) {
            return;
          }
        }
      }
      state.products.push(action.payload.product);
      updateDB(state.products, action.payload.loggedIn, action.payload.userid);
      createNotification("success", "Added To Wish List");
    },
    updateWishList(state, action) {
      state.products = action.payload.products;
    },
    setWishlistLoader(state, action) {
      state.wishlistLoader = action.payload.loader;
    },
    deleteWishList(state, action) {
      state.products.splice(action.payload.index, 1);
      updateDB(state.products, action.payload.loggedIn, action.payload.userid);
      createNotification("success", "Deleted From Wish List");
    },
    removeWishList(state, action) {
      for (const index in state.products) {
        if (state.products[index].id === action.payload.id) {
          state.products.splice(index, 1);
        }
      }
      updateDB(state.products, action.payload.loggedIn, action.payload.userid);
      createNotification("success", "Deleted From Wish List");
    },
    clearWishList(state) {
      state.products = null;
    },
  },
});

export const wishlistStoreActions = wishlistStore.actions;

const getWishListData = (state) => state.wishlistStore.products;

const updateDB = async (data, loggedIn, userid) => {
  let inputData = [];
  for (const item of data) {
    inputData.push(item.id);
  }
  await customerApi
    .put("/wishlist", {
      user_id: userid,
      loggedIn: loggedIn,
      products: inputData,
    })
    .then((res) => {
      console.log(res.data);
    });
};

export const getWishListTotalCount = createSelector(
  [getWishListData],
  (products) => {
    return products.length | 0;
  }
);

export const isWishListed = (id) =>
  createSelector([getWishListData], (products) => {
    for (const item of products) {
      if (item.id === id) return true;
    }
    return false;
  });

export const getWishList = createSelector([getWishListData], (products) => {
  return products;
});

export default wishlistStore;
