import { configureStore } from "@reduxjs/toolkit";
import cartStore, { cartStoreActions } from "./cart";
import wishlistStore, { wishlistStoreActions } from "./wishlist";
import checkoutStore from "./checkout";
import accountStore from "./account";
import categoryStore from "./category";
import formsStore from "./forms";
import generalStore, { generalStoreActions } from "./general";
import { customerApi } from "@/api/api";

const store = configureStore({
  reducer: {
    cartStore: cartStore.reducer,
    wishlistStore: wishlistStore.reducer,
    checkoutStore: checkoutStore.reducer,
    accountStore: accountStore.reducer,
    categoryStore: categoryStore.reducer,
    formsStore: formsStore.reducer,
    generalStore: generalStore.reducer,
  },
});

export default store;

export const loadSetting = async () => {
  console.log("testing");
  await Promise.all([
    customerApi
      .get("/general")
      .then((res) => {
        console.log("general: ", res.data);
        store.dispatch(
          generalStoreActions.updateDefaultAcceptedPayment({
            default_accepted_payment: res.data.data.default_payment_accepted,
          })
        );
        store.dispatch(
          generalStoreActions.updateShipping({
            shipping: res.data.data.shipping,
          })
        );
        store.dispatch(
          generalStoreActions.updatePickup({
            pickup: res.data.data.pickup ? res.data.data.pickup.pickup : [],
          })
        );
        store.dispatch(
          generalStoreActions.updateAddress({
            address: res.data.data.company_address,
          })
        );
        store.dispatch(
          generalStoreActions.updateSiteLogo({
            site_logo: res.data.data.company_image,
          })
        );
        store.dispatch(
          generalStoreActions.updateCompanyName({
            company_name:
              res.data.data.company_address &&
              res.data.data.company_address.name
                ? res.data.data.company_address.name
                : "",
          })
        );
        let currency_type = process.env.NEXT_PUBLIC_DEFAULT_CURRENCY;
        if (res.data.data && res.data.data.currency_type) {
          currency_type = res.data.data.currency_type;
        }
        store.dispatch(
          generalStoreActions.updateCurrencyType({
            currency_type: currency_type.toUpperCase(),
          })
        );
      })
      .catch((err) => {
        console.log(err);
      }),
    customerApi
      .get("/site/social-media")
      .then((res) => {
        if (res.data.success === true)
          store.dispatch(
            generalStoreActions.updateSocialMedia({
              social_media: res.data.data,
            })
          );
      })
      .catch((err) => {
        console.log(err);
      }),
    ,
  ]).catch((err) => {
    console.log(err);
  });
};

export const loadWishlist = async () => {
  store.dispatch(wishlistStoreActions.setWishlistLoader({ loader: true }));
  await customerApi
    .get("/wishlist", {
      withCredentials: true,
    })
    .then((res) => {
      let data = res.data.data || [];
      let wishlistData = [];
      if (data.length > 0) {
        for (const item of data) {
          wishlistData.push({
            name: item.name,
            id: item._id,
            image:
              item.image && item.image[0]
                ? process.env.NEXT_PUBLIC_UPLOADS + "/products/" + item.image[0]
                : "",
            price_type: item.price_type,
            price: item.price,
            qty: 1,
            exactQty: item.stock === -1 ? 999999 : item.stock,
            partNo: item.details.map((item) => {
              if (item.title.toLowerCase() === "part no") return item.value;
            }),
            offer: item.offer,
            tax: item.tax_rate,
            slug: item.slug,
            reseller_id: item.reseller_id,
            other_category: item.other_category,
            category_group: item.category_group,
          });
        }
      }
      store.dispatch(
        wishlistStoreActions.updateWishList({ products: wishlistData })
      );
      store.dispatch(wishlistStoreActions.setWishlistLoader({ loader: false }));
    })
    .catch((err) => {
      console.log(err);
      store.dispatch(wishlistStoreActions.setWishlistLoader({ loader: false }));
    });
};

export const loadCart = async (type = "") => {
  store.dispatch(wishlistStoreActions.updateWishList({ products: [] }));
  store.dispatch(cartStoreActions.setCartLoader({ loader: true }));
  const BeforeCartData = store.getState().cartStore.products;
  let currentCartData = [...BeforeCartData];
  await customerApi
    .get("/cart", {
      withCredentials: true,
    })
    .then((res) => {
      let data = res.data.data || [];
      let cartData = [];
      console.log(res.data.data);
      let currentCartQnty = {};
      if (currentCartData && currentCartData.length > 0) {
        for (const index in currentCartData) {
          currentCartQnty[currentCartData[index].id] = {
            _id: currentCartData[index].id,
            qty: currentCartData[index].qty,
          };
        }
      }
      if (data.length > 0) {
        for (const item of data) {
          let qty = 1;
          if (
            type === "login" &&
            currentCartQnty &&
            currentCartQnty[item._id] &&
            currentCartQnty[item._id].qty > 0 &&
            currentCartQnty[item._id]._id === item._id
          ) {
            qty = currentCartQnty[item._id].qty;
            for (const index in currentCartData) {
              if (item._id === currentCartData[index].id) {
                currentCartData.splice(index, 1);
              }
            }
          }
          cartData.push({
            name: item.name,
            id: item._id,
            image:
              item.image && item.image[0]
                ? process.env.NEXT_PUBLIC_UPLOADS + "/products/" + item.image[0]
                : "",
            price_type: item.price_type,
            price: item.price,
            qty: qty,
            exactQty: item.stock === -1 ? 999999 : item.stock,
            offer: item.offer,
            slug: item.slug,
            reseller_id: item.reseller_id,
            tax: item.tax_rate,
            partNo: item.category[item.category.length - 1].name || null,
            brand: item.details.map((item) => {
              if (item.title.toLowerCase() === "part no") return item.value;
            }),
            other_category: item.other_category,
            category_group: item.category_group,
          });
        }
      }
      if (type === "login" && currentCartData && currentCartData.length > 0) {
        cartData = [...cartData, ...currentCartData];
      }

      store.dispatch(cartStoreActions.updateCart({ products: cartData }));
      store.dispatch(cartStoreActions.setCartLoader({ loader: false }));
    })
    .catch((err) => {
      console.log("carterr", err);
      store.dispatch(cartStoreActions.updateCart({ products: [] }));
      store.dispatch(cartStoreActions.setCartLoader({ loader: false }));
    });
};
