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";

// Thunk for getting all CARTS
export const getAllWishlist = createAsyncThunk(
  "get-all-wishlist",
  async (_, { rejectWithValue }) => {
    try {
      const response = await GET(API.WISHLIST);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  },
);

// Thunk for Checking itme in  CART
export const checkInWishlist = createAsyncThunk(
  "check-in-wishlist",
  async (product_id, { rejectWithValue }) => {
    try {
      const response = await GET(API.CHECk_ITEM_IN_WISHLIST + `/${product_id}`);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  },
);

// Thunk for posting CART
export const postWishlist = createAsyncThunk(
  "post-cart",
  async ({ product_id }, { rejectWithValue }) => {
    try {
      const response = await POST(`${API.WISHLIST}/${product_id}`);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  },
);

// Create the slice
const wishlitSlice = createSlice({
  name: "wishlist",
  initialState: {
    allWishlist: [],
    storeInFav: false,
    error: null,
    status: "idle",
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getAllWishlist.pending, (state) => {
        state.status = "loading";
      })
      .addCase(getAllWishlist.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.allWishlist = action.payload?.data || [];
      })
      .addCase(getAllWishlist.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
      })

      .addCase(checkInWishlist.pending, (state) => {
        state.status = "loading";
      })
      .addCase(checkInWishlist.fulfilled, (state, action) => {
        state.status = "succeeded";

        state.itemInWishlist = action.payload?.data?.is_wishlisted || false;
      })
      .addCase(checkInWishlist.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
      })

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

export default wishlitSlice.reducer;
