import { createSlice } from "@reduxjs/toolkit";
import { createSelector } from "@reduxjs/toolkit";
import moment from "moment-timezone";
import { createNotification } from "@/customHook/useNotification";

const initialState = {
  address: {
    name: "",
    address_1: "",
    address_2: "",
    landmark: "",
    country: "",
    state: "",
    phone: "",
    zip_code: "",
    address_id: "",
  },
  delivery_charge: 0,
  free_shipping_above: null,
  free_shipping_above_country: [],
  cod_charge: 0,
  estimated_delivery: "",
  cart: [],
  discount: { code: "", percentage: "", category: "" },
  special_shipping: [],
  standard_shipping_day: 0,
  delivery_type: { type: "standard", id: "" },
  ship_or_pickup: "",
  otherSellersProducts: [],
  otherSellersCart: [],
  pickup: { name: "", address: "", phone: "" },
  pickup_date: "",
  contact_phone: "",
};
const checkoutStore = createSlice({
  name: "checkoutStoreAction",
  initialState: initialState,
  reducers: {
    updateShipOrPickup(state, action) {
      state.ship_or_pickup = action.payload.ship_or_pickup;
    },
    updatePickupDate(state, action) {
      state.pickup_date = action.payload.pickup_date;
    },
    updateContactPhone(state, action) {
      state.contact_phone = action.payload.contact_phone;
    },
    updateDeliveryCharge(state, action) {
      state.delivery_charge = action.payload.delivery_charge;
    },
    updateSelectedPickup(state, action) {
      state.pickup = action.payload.pickup;
    },
    updateFreeShippingAbove(state, action) {
      state.free_shipping_above = action.payload.free_shipping_above;
    },
    updateFreeShippingAboveCountry(state, action) {
      state.free_shipping_above_country =
        action.payload.free_shipping_above_country;
    },
    updateSpecialShipping(state, action) {
      state.special_shipping = action.payload.special_shipping;
    },
    updateSelectedDeliveryType(state, action) {
      state.delivery_type = action.payload.delivery_type;
    },
    updateCodCharge(state, action) {
      state.cod_charge = action.payload.cod_charge;
    },
    updateDiscount(state, action) {
      state.discount = action.payload.discount;
    },
    updateStandardEstimatedDelivery(state, action) {
      state.estimated_delivery = action.payload.estimated_delivery;
      state.standard_shipping_day = action.payload.standard_shipping_day;
    },
    storeAddress(state, action) {
      state.address = action.payload.address;
    },
    storeCart(state, action) {
      state.cart = action.payload.cart;
    },
    updateDeliveryForOtherSellers(state, action) {
      if (state.otherSellersCart.length > 0) {
        let data = [];
        for (const index in state.otherSellersCart) {
          let newData = JSON.stringify(state.otherSellersCart[index]);
          newData = JSON.parse(newData);
          console.log("state.otherSellersCart: newData1", newData);
          if (newData.delivery_type.reseller_id == action.payload.reseller_id) {
            newData["delivery_type"] = action.payload.delivery_type;
            newData["delivery_charge"] = action.payload.delivery_charge;
            console.log("state.otherSellersCart: newData2", newData);
          }
          data.push(newData);
        }
        console.log("state.otherSellersCart: data", data);
        state.otherSellersCart = data;
      }
    },
    updatePickupForOtherSellers(state, action) {
      if (state.otherSellersCart.length > 0) {
        let data = [];
        for (const index in state.otherSellersCart) {
          let newData = JSON.stringify(state.otherSellersCart[index]);
          newData = JSON.parse(newData);
          console.log("state.otherSellersCart: newData1", newData);
          if (newData.delivery_type.reseller_id == action.payload.reseller_id) {
            newData["selected_pickup"] = action.payload.pickup;
            console.log("state.otherSellersCart: newData2", newData);
          }
          data.push(newData);
        }
        console.log("state.otherSellersCart: data", data);
        state.otherSellersCart = data;
      }
    },
    storeOtherSellersCart(state, action) {
      state.otherSellersCart = action.payload.otherSellersCart;
    },
    storeOtherSellersProducts(state, action) {
      state.otherSellersProducts = action.payload.otherSellersProducts;
    },
    clearAddress(state) {
      state.address = {
        name: "",
        address_1: "",
        address_2: "",
        landmark: "",
        country: "",
        state: "",
        phone: "",
        zip_code: "",
        address_id: "",
      };
    },
    clearCart(state) {
      state.cart = [];
      state.otherSellersProducts = [];
      state.otherSellersCart = [];
    },
    clearDiscount(state) {
      state.discount = { code: "", percentage: "", category: "" };
    },
    clearPickup(state) {
      state.pickup = { name: "", address: "", phone: "" };
      state.pickup_date = "";
    },
    cleactContactPhone(state) {
      state.contact_phone = "";
    },
  },
});

export const checkoutStoreActions = checkoutStore.actions;

const getAddressData = (state) => state.checkoutStore.address;
const getCartData = (state) => state.checkoutStore.cart;
const getOtherSellerProductCartData = (state) =>
  state.checkoutStore.otherSellersCart;
const getDiscount = (state) => state.checkoutStore.discount;
const getShipping = (state) => state.generalStore.shipping;
const getContactPhone = (state) => state.checkoutStore.contact_phone;
const getPickup = (state) => state.generalStore.pickup;
const getPickupDate = (state) => state.checkoutStore.pickup_date;
const getShipOrPickup = (state) => state.checkoutStore.ship_or_pickup;
const getSelectedPickup = (state) => state.checkoutStore.pickup;
const getDeliveryType = (state) => state.checkoutStore.delivery_type;
const getDeliveryCharge = (state) => state.checkoutStore.delivery_charge;
const getFreeShippingAbove = (state) => state.checkoutStore.free_shipping_above;
const getFreeShippingAboveCountry = (state) =>
  state.checkoutStore.free_shipping_above_country;
const getCodCharge = (state) => state.checkoutStore.cod_charge;
const getEstimatedDelivery = (state) => state.checkoutStore.estimated_delivery;

export const validateAddress = createSelector([getAddressData], (address) => {
  console.log("test", address);
  for (const item in address) {
    if (
      item == "zip_code" ||
      item == "landmark" ||
      item == "address_id" ||
      item == "delivery_charge"
    )
      continue;
    if (!address[item]) {
      return false;
    }
  }
  return true;
});

export const getCheckoutCart = createSelector(
  [
    getCartData,
    getShipping,
    getOtherSellerProductCartData,
    getDiscount,
    getPickup,
  ],
  (cart, shipping, otherSellerProductCart, discount, pickup) => {
    let newCart = [];

    let mainProducts = [];

    let oldCart = cart.map((item) => {
      return { ...item, discount_percentage: "" };
    });

    // Main Product Cart
    for (let item of oldCart) {
      console.log("item.categories", discount);
      let price = 0;
      if (item.price_type === "quantity_wise") {
        for (const priceItem of item.price) {
          if (item.qty <= priceItem.quantity) {
            price = Number(priceItem.price);
            break;
          }
        }
      } else {
        price = Number(item.price);
      }

      let total_price = 0;
      let grand_total = 0;
      let total_before_tax = 0;
      total_price = item.qty * price;
      grand_total = item.qty * price;
      total_before_tax = item.qty * price;
      // Discount
      if (discount && discount.code && discount.percentage) {
        if (discount.category && discount.category.length > 0) {
          let foundCat = false;
          if (item.other_category && item.other_category.length > 0) {
            for (const innerItem of item.other_category) {
              for (const discountCat of discount.category) {
                if (innerItem == discountCat) {
                  item["discount_percentage"] = discount.percentage;
                  foundCat = true;
                  break;
                }
              }
            }
          } else if (foundCat == false && item.category_group) {
            if (discount.category.includes(item.other_category)) {
              item["discount_percentage"] = discount.percentage;
            }
          }
        } else {
          item["discount_percentage"] = discount.percentage;
        }
      }
      //
      if (item.offer) {
        const offer = (item.offer / 100) * grand_total;
        grand_total = grand_total - offer;
        total_before_tax = total_before_tax - offer;
      }
      if (item.tax) {
        console.log("item.tax: ", item.tax);
        const tax = (item.tax / 100) * grand_total;
        console.log("grand_total: ", grand_total);
        console.log("tax", tax);
        grand_total = grand_total + tax;
      }
      if (item.discount_percentage) {
        const discount_percentage =
          (item.discount_percentage / 100) * grand_total;
        grand_total = grand_total - discount_percentage;
      }
      mainProducts.push({
        ...item,
        total_price: total_price.toFixed(2),
        grand_total: grand_total.toFixed(2),
        total_before_tax: total_before_tax.toFixed(2),
      });
    }
    if (mainProducts.length > 0) {
      newCart.push({
        products: mainProducts,
        shipping: shipping,
        pickup: pickup,
      });
    }

    // Other Sellers Product Cart
    let oldOtherSellerProductCart = otherSellerProductCart.map((item) => {
      if (item && item.products) {
        let products = item.products.map((innerItem) => {
          return { ...innerItem, discount_percentage: "" };
        });
        return { ...item, products: products };
      }
    });
    console.log("oldOtherSellerProductCart: ", oldOtherSellerProductCart);
    if (oldOtherSellerProductCart && oldOtherSellerProductCart.length > 0) {
      for (let item of oldOtherSellerProductCart) {
        let otherSellerProducts = [];
        let reseller_id = "";
        if (item && item.products && item.products.length > 0) {
          for (let productItem of item.products) {
            console.log("item.categories", discount);
            let price = 0;
            if (productItem.price_type === "quantity_wise") {
              for (const priceItem of productItem.price) {
                if (productItem.qty <= priceItem.quantity) {
                  price = Number(priceItem.price);
                  break;
                }
              }
            } else {
              price = Number(productItem.price);
            }

            let total_price = 0;
            let grand_total = 0;
            let total_before_tax = 0;
            total_price = productItem.qty * price;
            grand_total = productItem.qty * price;
            total_before_tax = productItem.qty * price;
            // Discount
            if (discount && discount.code && discount.percentage) {
              if (discount.category && discount.category.length > 0) {
                let foundCat = false;
                if (
                  productItem.other_category &&
                  productItem.other_category.length > 0
                ) {
                  for (const innerItem of productItem.other_category) {
                    for (const discountCat of discount.category) {
                      if (innerItem == discountCat) {
                        productItem["discount_percentage"] =
                          discount.percentage;
                        foundCat = true;
                        break;
                      }
                    }
                  }
                } else if (foundCat == false && productItem.category_group) {
                  if (discount.category.includes(productItem.other_category)) {
                    productItem["discount_percentage"] = discount.percentage;
                  }
                }
              } else {
                productItem["discount_percentage"] = discount.percentage;
              }
            }
            //
            if (productItem.offer) {
              const offer = (productItem.offer / 100) * grand_total;
              grand_total = grand_total - offer;
              total_before_tax = total_before_tax - offer;
            }
            if (productItem.tax) {
              console.log("productItem.tax: ", productItem.tax);
              const tax = (productItem.tax / 100) * grand_total;
              console.log("grand_total: ", grand_total);
              console.log("tax", tax);
              grand_total = grand_total + tax;
            }
            if (productItem.discount_percentage) {
              const discount_percentage =
                (productItem.discount_percentage / 100) * grand_total;
              grand_total = grand_total - discount_percentage;
            }
            otherSellerProducts.push({
              ...productItem,
              total_price: total_price.toFixed(2),
              grand_total: grand_total.toFixed(2),
              total_before_tax: total_before_tax.toFixed(2),
            });
            if (!reseller_id) reseller_id = productItem.reseller_id;
          }
          if (otherSellerProducts.length > 0) {
            newCart.push({
              products: otherSellerProducts,
              shipping: item.shipping,
              pickup: item.pickup,
              selected_pickup: item.selected_pickup,
              delivery_type: item.delivery_type,
              delivery_charge: item.delivery_charge,
              reseller_id: item.delivery_type.reseller_id,
            });
          }
        }
      }
    }
    console.log("newCart: ", newCart);
    return newCart;
  }
);

export const getTotalStats = createSelector(
  [
    getDeliveryCharge,
    getEstimatedDelivery,
    getFreeShippingAbove,
    getFreeShippingAboveCountry,
    getCodCharge,
    getAddressData,
    getCheckoutCart,
  ],
  (
    delivery_charge,
    estimated_delivery,
    free_shipping_above,
    free_shipping_above_country,
    cod_charge,
    addressData,
    checkoutCartData
  ) => {
    let finalDeliveryCharge = 0;
    let estimatedDelivery = estimated_delivery;
    let beforeDiscount = 0;
    let itemCount = 0;
    let codCharge = 0;
    let totalPrice = 0;
    let beforePrice = 0;
    let grandTotal = 0;
    let totalSaving = 0;

    console.log("checkoutCartData123: ", checkoutCartData);
    // Main Product Cart Section
    if (checkoutCartData && checkoutCartData.length > 0) {
      for (const cart of checkoutCartData) {
        for (const item of cart.products) {
          let price = 0;
          if (item.price_type === "quantity_wise") {
            for (const priceItem of item.price) {
              if (item.qty <= priceItem.quantity) {
                price = Number(priceItem.price);
                break;
              }
            }
          } else {
            price = Number(item.price);
          }

          totalPrice = 0;
          beforePrice = beforePrice + item.qty * price;
          let currentProductPrice = price * item.qty;
          if (item.offer && item.offer > 0) {
            const offer = (item.offer / 100) * (price * item.qty);
            currentProductPrice = currentProductPrice - offer;
          }
          if (item.tax && item.tax > 0) {
            const tax = (item.tax / 100) * currentProductPrice;
            currentProductPrice = currentProductPrice + tax;
          }
          beforeDiscount = Number(beforeDiscount) + Number(currentProductPrice);
          if (item.discount_percentage && item.discount_percentage > 0) {
            const discount_percentage =
              (item.discount_percentage / 100) * currentProductPrice;
            grandTotal = Number(grandTotal) - Number(discount_percentage);
          }
          grandTotal = Number(grandTotal) + Number(currentProductPrice);
          console.log("checkoutCartData123 -c", Number(currentProductPrice));
        }
        totalPrice = Number(grandTotal.toFixed(2));
        console.log("checkoutCartData123 -", Number(totalPrice));
        grandTotal = Number(grandTotal.toFixed(2));
        beforeDiscount = beforeDiscount.toFixed(2);
        itemCount =
          Number(itemCount) +
          Number(cart && cart.products ? cart.products.length : 0);

        let deliveryCharge = 0;
        if (!cart.reseller_id) {
          // For Main Seller Products
          deliveryCharge = Number(delivery_charge);
          // COD Charge
          if (cod_charge && cod_charge > 0) {
            codCharge = codCharge + cod_charge;
          }
          // Free Shipping Above
          let foundCountryWise = false;
          if (
            free_shipping_above_country &&
            free_shipping_above_country.length > 0
          ) {
            for (const item of free_shipping_above_country) {
              if (addressData.country == item.name) {
                if (item && item.charge >= 0) {
                  if (Number(grandTotal) >= item.charge) {
                    deliveryCharge = 0;
                  }
                  foundCountryWise = true;
                }
                break;
              }
            }
          }
          if (
            foundCountryWise === false &&
            free_shipping_above &&
            free_shipping_above >= 0
          ) {
            if (Number(grandTotal) >= free_shipping_above) {
              deliveryCharge = 0;
            }
          }
        } else {
          // For Other Seller Products
          let shipping = cart.shipping;
          deliveryCharge = Number(cart.delivery_charge) || 0;
          // COD Charge
          if (shipping && shipping.codCharge && shipping.codCharge > 0) {
            codCharge = codCharge + shipping.codCharge;
          }
          // Free Shipping Above
          let foundCountryWise = false;
          if (
            shipping.free_shipping_above_country &&
            shipping.free_shipping_above_country.length > 0
          ) {
            for (const item of shipping.free_shipping_above_country) {
              if (addressData.country == item.name) {
                if (item && item.charge >= 0) {
                  if (Number(grandTotal) >= item.charge) {
                    deliveryCharge = 0;
                  }
                  foundCountryWise = true;
                }
                break;
              }
            }
          }
          if (
            foundCountryWise === false &&
            shipping.free_shipping_above &&
            shipping.free_shipping_above >= 0
          ) {
            if (Number(grandTotal) >= shipping.free_shipping_above) {
              deliveryCharge = 0;
            }
          }
        }
        finalDeliveryCharge =
          Number(finalDeliveryCharge) + Number(deliveryCharge);
      }
    }
    //

    totalSaving = (beforePrice - grandTotal).toFixed(2);
    grandTotal = Number(grandTotal) + Number(finalDeliveryCharge);
    grandTotal = Number(grandTotal.toFixed(2));
    return {
      deliveryCharge: finalDeliveryCharge,
      itemCount,
      totalPrice,
      grandTotal,
      totalSaving,
      estimatedDelivery,
      cod_charge: codCharge,
      beforeDiscount,
    };
  }
);

export const getPaymentInput = createSelector(
  [
    getCartData,
    getDeliveryCharge,
    getAddressData,
    getEstimatedDelivery,
    getDiscount,
    getDeliveryType,
    getOtherSellerProductCartData,
    getSelectedPickup,
    getShipOrPickup,
    getPickupDate,
    getContactPhone,
  ],
  (
    cart,
    delivery_charge,
    address,
    estimated_delivery,
    discount,
    delivery_type,
    otherSellerProductCartData,
    pickup,
    ship_or_pickup,
    pickup_date,
    contact_phone
  ) => {
    const paymentInput = {
      product: [],
      billing_address: address,
      shipping_address: address,
      delivery_charge: delivery_charge,
      estimated_delivery: estimated_delivery,
      discount_code: discount.code,
      delivery_type: delivery_type,
      pickup: pickup,
      contact_phone: contact_phone,
      pickup_date: pickup_date,
      ship_or_pickup: ship_or_pickup,
      otherSellerProduct: [],
    };
    paymentInput.product = cart.map((item) => {
      return { id: item.id, qnty: item.qty };
    });
    paymentInput.otherSellerProduct = otherSellerProductCartData.map((item) => {
      let output = {
        product: [],
        delivery_type: item.delivery_type,
        pickup: item.selected_pickup,
      };
      for (const product of item.products) {
        output.product.push({
          id: product.id,
          qnty: product.qty,
          resellerID: product.reseller_id,
        });
      }
      return { ...output };
    });
    return paymentInput;
  }
);

export default checkoutStore;
