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

const initialState = {
  products: [],
  cartLoader: true,
};
const cartStore = createSlice({
  name: "cartStoreAction",
  initialState: initialState,
  reducers: {
    addCart(state, action) {
      if (state.products.length > 0) {
        for (const item of state.products) {
          if (item.id == action.payload.product.id) {
            let newQty =
              parseInt(item.qty) + parseInt(action.payload.product.qty);
            if (item.exactQty == -1) {
              item.qty = newQty;
            } else if (newQty > item.exactQty) {
              item.qty = item.exactQty;
            } else item.qty = newQty;
            createNotification("success", "Added to cart");
            return;
          }
        }
      }
      state.products.push(action.payload.product);
      updateDB(state.products, action.payload.loggedIn, action.payload.userid);
      createNotification("success", "Added to cart");
    },
    updateCart(state, action) {
      state.products = action.payload.products;
      updateDB(state.products, action.payload.loggedIn, action.payload.userid);
    },
    setCartLoader(state, action) {
      state.cartLoader = action.payload.loader;
    },
    updateProductQty(state, action) {
      let newQty = action.payload.value;
      if (state.products[action.payload.index].exactQty == -1) {
        state.products[action.payload.index].qty = newQty;
      } else if (newQty > state.products[action.payload.index].exactQty) {
        state.products[action.payload.index].qty =
          state.products[action.payload.index].exactQty;
      } else state.products[action.payload.index].qty = newQty;
    },
    deleteCart(state, action) {
      state.products.splice(action.payload.index, 1);
      updateDB(state.products, action.payload.loggedIn, action.payload.userid);
      createNotification("success", "Removed From cart");
    },
    clearCart(state) {
      state.products = null;
    },
  },
});

export const cartStoreActions = cartStore.actions;

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

const getCartData = (state) => state.cartStore.products;

export const getCartTotalPrice = createSelector([getCartData], (products) => {
  console.log("products: ", products);
  let total = 0;
  for (const item of products) {
    let exactPrice = 0;
    if (item.price_type === "quantity_wise") {
      for (const priceItem of item.price) {
        if (item.qty <= priceItem.quantity) {
          exactPrice = Number(priceItem.price);
          break;
        }
      }
    } else {
      exactPrice = Number(item.price);
    }
    let price = exactPrice * item.qty;
    if (item.offer) {
      price =
        exactPrice * item.qty - (item.offer / 100) * (exactPrice * item.qty);
    }
    total = total + price;
  }
  return total;
});

export const getCartExactTotalPrice = createSelector(
  [getCartData],
  (products) => {
    let total = 0;
    for (const item of products) {
      let exactPrice = 0;
      if (item.price_type === "quantity_wise") {
        for (const priceItem of item.price) {
          if (item.qty <= priceItem.quantity) {
            exactPrice = Number(priceItem.price);
            break;
          }
        }
      } else {
        exactPrice = Number(item.price);
      }

      let price = exactPrice * item.qty;
      total = total + price;
    }
    return total;
  }
);

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

export const getCartList = createSelector([getCartData], (products) => {
  return products;
});

export default cartStore;
