import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { DELETE, GET, POST } from "../../utils/api";
import { API } from "../../endpoints/common_endpoints";
import { useSelector } from "react-redux";
import Cookies from "js-cookie";
import { variant_type } from "../../utils/common";

// Thunk for getting all CARTS

export const postCart = createAsyncThunk(
  "post-cart",
  async ({ data, isSignIn }, { rejectWithValue }) => {
    try {
      if (isSignIn) {
        const response = await POST(API.CART, data);
        return response;
      } else {
        const item = {
          quantity: Number(data?.quantity || 1),
          product_id: data?.product_id,

          variant_id: data?.variant_id || null,
          d_variant_id: data?.d_variant_id || null,
          t_variant_id: data?.t_variant_id || null,
          variant_type_id: data?.variant_type_id,

          Product: {
            name: data?.product_name,
            image: data?.image,
            tax_percentage: data?.tax_percentage,
          },

          Product_Variant: {
            name: data?.variant_name,
            mrp: data?.mrp,
            price: data?.price,
            description: data?.description,
          },
        };

        const existingCart = Cookies.get("arc_diamond_cart");
        let updatedCart = existingCart ? JSON.parse(existingCart) : [];

        // 🔑 find same variant item
        const existingItemIndex = updatedCart.findIndex((cartItem) => {
          if (
            cartItem.product_id !== item.product_id ||
            cartItem.variant_type_id !== item.variant_type_id
          ) {
            return false;
          }

          if (item.variant_type_id === variant_type.Single) {
            return cartItem.variant_id === item.variant_id;
          }

          if (item.variant_type_id === variant_type.Double) {
            return cartItem.d_variant_id === item.d_variant_id;
          }

          if (item.variant_type_id === variant_type.Triple) {
            return cartItem.t_variant_id === item.t_variant_id;
          }

          return false;
        });

        if (existingItemIndex > -1) {
          updatedCart[existingItemIndex].quantity =
            Number(updatedCart[existingItemIndex].quantity) + item.quantity;
        } else {
          updatedCart.push(item);
        }

        Cookies.set("arc_diamond_cart", JSON.stringify(updatedCart));

        return {
          success: true,
          data: updatedCart,
        };
      }
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);


export const postCartQuantity = createAsyncThunk(
  "post-cart-quantity",
  async (data, { rejectWithValue }) => {
    try {

    
      
      if (data?.isSignIn) {
        const response = await POST(API.CART_QUANTITY, data);
        return response;
      } else {
        const cartFromCookies = Cookies.get("arc_diamond_cart");

        if (!cartFromCookies) {
          return { data: { success: false, data: null } };
        }

        const cartData = JSON.parse(cartFromCookies);

        const foundItemIndex = cartData.findIndex((item) => {
          if (
            item.product_id !== data.product_id ||
            item.variant_type_id !== data.variant_type_id
          ) {
            return false;
          }

          if (data.variant_type_id === variant_type.Single) {
            return item.variant_id === data.variant_id;
          }

          if (data.variant_type_id === variant_type.Double) {
            return item.d_variant_id === data.d_variant_id;
          }

          if (data.variant_type_id === variant_type.Triple) {
            return item.t_variant_id === data.t_variant_id;
          }

          return false;
        });

        if (foundItemIndex > -1) {
          if (data?.type === "add") {
            cartData[foundItemIndex].quantity += 1;
          } else if (data?.type === "minus") {
            if (cartData[foundItemIndex].quantity > 1) {
              cartData[foundItemIndex].quantity -= 1;
            } else {
              cartData.splice(foundItemIndex, 1);
            }
          }

          Cookies.set("arc_diamond_cart", JSON.stringify(cartData));
          return { data: { success: true, data: cartData } };
        }

        return { data: { success: false, data: null } };

      }
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);


export const addToCard = createAsyncThunk(
  "auth/add-to-card",
  async (data, { rejectWithValue }) => {
    try {
      const response = await POST(API.CART, data);

      return response?.data?.token;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  },
);

// Thunk for getting all CARTS
export const getAllCart = createAsyncThunk(
  "get-all-cart",
  async (isSignIn, { rejectWithValue }) => {
    try {
      if (isSignIn) {
        const response = await GET(API.CART);
        return response;
      } else {
        const cartFromCookies = Cookies.get("arc_diamond_cart");

        if (cartFromCookies) {
          // Ensure the data is parsed correctly if it's a string
          let cartData = cartFromCookies;
          try {
            // Only parse if cartFromCookies is a string
            if (typeof cartFromCookies === "string") {
              cartData = JSON.parse(cartFromCookies);
            }
            const response = await POST(
              API.GET_ALL_CART_WITHOUT_LOGIN,
              cartData,
            );

            if (response?.data?.dataToIndex?.length > 0) {
              const cartFromCookies = Cookies.get("arc_diamond_cart");
              const cartIndexesFromCookies = JSON.parse(
                cartFromCookies || "[]",
              );
              cartIndexesFromCookies.forEach((index) => {
                if (index >= 0 && index < cartData.length) {
                  cartData.splice(index, 1);
                }
              });
            }
            return response?.data;
          } catch (error) {
            console.error("Error parsing cart data:", error);
            return [];
          }
        } else {
          return [];
        }
      }
    } catch (error) {
      return rejectWithValue(error.message);
    }
  },
);
// Thunk for getting CART
export const getCart = createAsyncThunk(
  "get-cart",
  async ({ id, isSignIn }, { rejectWithValue }) => {
    try {
      const response = await GET(API.CART + `/${id}`);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  },
);

export const postToLoginCart = createAsyncThunk(
  "post-all-to-cart",
  async (_, { rejectWithValue }) => {
    try {
      let cartItems = [];
      const existingCart = Cookies.get("arc_diamond_cart");

      if (existingCart) {
        cartItems = JSON.parse(existingCart);
      }

      // Check if there are any items in the cart
      if (cartItems.length > 0) {
        // Post each cart item and wait for all responses
        const postResponses = await Promise.all(
          cartItems.map(async (value) => {
            const response = await POST(API.CART, value);
            return response?.data?.data;
          }),
        );

        // Check if all responses were successful (status code 200)
        const allSuccess = postResponses.every(
          (response) => response?.status === 200,
        );
        await Cookies.remove("arc_diamond_cart");
        // If all items were successfully posted, remove the cookies and return success
        if (allSuccess) {
         
          await Cookies.remove("arc_diamond_cart");
          return { success: true };
        } else {
          // If any item failed, reject the thunk with a failure message
       
          return rejectWithValue("Failed to post some items to the cart");
        }
      } else {
        // If no items in the cart, just remove cookies and return success
       
        await Cookies.remove("arc_diamond_cart");
        return { success: true };
      }
    } catch (error) {
      console.error("Error in posting cart items:", error);
      return rejectWithValue(error.message);
    }
  },
);
// Thunk for Checking itme in  CART

// Thunk for posting CART

// Thunk for Change Quanitity

// Thunk for delete cart
export const deleteAllCart = createAsyncThunk(
  "delete-cart",
  async ({ id, isSignin, product_id, varient_id }, { rejectWithValue }) => {
    try {
      if (isSignin) {
        const response = await DELETE(API.CART + `/${id}`);
        return response?.data;
      } else {
        const cartData = Cookies.get("arc_diamond_cart");
        if (cartData) {
          let cart = JSON.parse(cartData);

          const updatedCart = cart.filter(
            (item) =>
              !(
                item.product_id === product_id && item.variant_id === varient_id
              ),
          );

          Cookies.set("arc_diamond_cart", JSON.stringify(updatedCart), {
            expires: 7,
            path: "/",
          });

          return { success: true };
        } else {
          return { success: false, message: "No cart found in cookies" };
        }
      }
    } catch (error) {
      return rejectWithValue(error.message);
    }
  },
);

// Create the slice
const cartSlice = createSlice({
  name: "cart",
  initialState: {
    allCarts: [],
    singleCart: {},
    Cart: false,
    error: null,
    status: "idle",
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getAllCart.pending, (state) => {
        state.status = "loading";
      
      })
      .addCase(getAllCart.fulfilled, (state, action) => {
        state.status = "succeeded";
       
        state.allCarts = action.payload || [];
      
      })
      .addCase(getAllCart.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
       
      })

      .addCase(getCart.pending, (state) => {
        state.status = "loading";
       
      })
      .addCase(getCart.fulfilled, (state, action) => {
        state.status = "succeeded";
        
        state.singleCart = action.payload?.data || {};
        
      })
      .addCase(getCart.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
       
      })

      .addCase(postCart.pending, (state) => {
        state.status = "loading";
        
      })
      .addCase(postCart.fulfilled, (state, action) => {
        state.status = "succeeded";
       
      })
      .addCase(postCart.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
      
      })

      .addCase(postCartQuantity.pending, (state) => {
        state.status = "loading";
        
      })
      .addCase(postCartQuantity.fulfilled, (state, action) => {
        state.status = "succeeded";
       
        
      })
      .addCase(postCartQuantity.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
      
      })

      .addCase(addToCard.pending, (state) => {
        state.status = "loading";
       
      })
      .addCase(addToCard.fulfilled, (state, action) => {
        state.status = "succeeded";
       
      })
      .addCase(addToCard.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        
      })

      .addCase(deleteAllCart.pending, (state) => {
        state.status = "loading";
        
      })
      .addCase(deleteAllCart.fulfilled, (state, action) => {
        state.status = "succeeded";
       
      })
      .addCase(deleteAllCart.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
      
      });
  },
});

export default cartSlice.reducer;
