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

export const createOrderAddress = createAsyncThunk(
  "create-order-addrress",
  async ({ data }, { rejectWithValue }) => {
    try {
      const response = await POST(API.ORDER_ADDRESS, data);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const EditOrderAddress = createAsyncThunk(
  "create-order-addrress",
  async ({ id, data }, { rejectWithValue }) => {
    try {
     

      const response = await PUT(`${API.ORDER_ADDRESS}/${id}`, data);

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

export const getAllOrderAddress = createAsyncThunk(
  "get-order-addrress",
  async (data, { rejectWithValue }) => {
    try {
      const response = await GET(API.ORDER_ADDRESS);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const getAllSippingOrderAddress = createAsyncThunk(
  "get-sipping-order-addrress",
  async (data, { rejectWithValue }) => {
    try {
      const response = await GET(API.ORDER_ADDRESS + `/${"shipping"}`);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const getSingleOrderAddress = createAsyncThunk(
  "get-order-address-single",
  async ({ id }, { rejectWithValue }) => {
    try {
      const response = await GET(API.ORDER_ADDRESS + `/${id}`);
     

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

export const deleteAddress = createAsyncThunk(
  "delete-address",
  async (id, { rejectWithValue }) => {
    try {
      const response = await DELETE(API.ORDER_ADDRESS + `/${id}`);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);
// Thunk for getting all CARTS
export const createOrder = createAsyncThunk(
  "create-order",
  async (data, { rejectWithValue }) => {
    try {
      const response = await POST(API.ORDER, data);
     
      if (response?.success) {
        return response;
      } else {
        return rejectWithValue(response.errors);
      }
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

// Thunk for getting all CARTS
export const getAllOrder = createAsyncThunk(
  "get-all-orders",
  async ({ order_status_id = "" }, { rejectWithValue }) => {
    try {
      const response = await GET(
        API.ORDER + `?order_status_id=${order_status_id || ""}`
      );
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const getAllReturnOrder = createAsyncThunk(
  "get-all-return-orders",
  async ({ order_status_id = "" }, { rejectWithValue }) => {
    try {
      const response = await GET(
        API.ORDER + `/return/order?order_status_id=${order_status_id || ""}`
      );
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const getAllCancelOrder = createAsyncThunk(
  "get-all-cancel-orders",
  async ({ order_status_id = "" }, { rejectWithValue }) => {
    try {
      const response = await GET(
        API.ORDER + `/cancel/order?order_status_id=${order_status_id || ""}`
      );
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

// Thunk for getting CART
export const getOrder = createAsyncThunk(
  "get-order",
  async ({ id, order_status_id }, { rejectWithValue }) => {
    try {
      const response = await GET(
        API.ORDER + `/${id}?order_status_id=${order_status_id}`
      );
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const getSingleReturnOrder = createAsyncThunk(
  "get-retrun-order",
  async ({ id, order_status_id }, { rejectWithValue }) => {
    try {
      const response = await GET(
        API.ORDER + `/return/${id}?order_status_id=${order_status_id}`
      );
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const getSingleCancelOrder = createAsyncThunk(
  "get-cancel-order",
  async ({ id, order_status_id }, { rejectWithValue }) => {
    try {
      const response = await GET(
        API.ORDER + `/cancel/${id}?order_status_id=${order_status_id}`
      );
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

// Thunk for getting CART
export const cancelOrder = createAsyncThunk(
  "cancel-order",
  async ({ order_id, data }, { rejectWithValue }) => {
    try {
  

      const response = await POST(API.ORDER_CANCEL + `/${order_id}`, data);
      return response;
    } catch (error) {
      console.error("Cancel order failed:", error);
      return rejectWithValue(
        error.response?.data || error.message || "Something went wrong"
      );
    }
  }
);

// Thunk for getting CART
export const returnOrder = createAsyncThunk(
  "return-order",
  async ({ order_id, data }, { rejectWithValue }) => {
    try {
      const response = await POST(API.ORDER_RETURN + `/${order_id}`, data);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const createOrderMessage = createAsyncThunk(
  "create-order-message",
  async (data, { rejectWithValue }) => {
    try {
      const response = await POST(API.ORDER + `/message`, data);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const getOrderMessage = createAsyncThunk(
  "get-order-message",
  async (id, { rejectWithValue }) => {
    try {
      const response = await GET(API.ORDER + `/message/data`);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const CouponApplyed = createAsyncThunk(
  "coupon-applyed",
  async (data, { rejectWithValue }) => {
    try {
      const response = await POST(API.COUPON_APPLYED, data);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

// export const getCoupons = createAsyncThunk(
//   "get-coupon",
//   async (id, { rejectWithValue }) => {
//     try {
//       const response = await GET(API.COUPON);
//       return response;
//     } catch (error) {
//       return rejectWithValue(error.message);
//     }
//   }
// );

export const OrderCalculation = createAsyncThunk(
  "order-calculation",
  async (data, { rejectWithValue }) => {
    try {
      const response = await POST(API.ORDER_CALCULATION, data);
      if (response?.success) {
        return response;
      }

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

const handleAsyncState = (state, action, isSignin = false) => {
  switch (action.type) {
    case "pending":
      state.status = "loading";
      break;
    case "fulfilled":
      state.status = "succeeded";
      if (isSignin) {
        state.token = action.payload;
        state.is_signin = true;
      }
      break;
    case "rejected":
      state.status = "failed";
      state.error = action.payload;
      if (isSignin) state.is_signin = false;
      break;
    default:
      return state;
  }
};

// Create the slice
const orderSlice = createSlice({
  name: "order",
  initialState: {
    allOrders: [],
    allReturnOrders: [],
    allCancelOrders: [],
    allOrdersAddress: [],
    allSppingOrdersAddress: [],
    orderAddress: {},
    order: {},
    returnOrder: {},
    cancelOrder: {},
    orderMessage: [],
    all_coupons: [],
    error: null,
    status: "idle",
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(createOrder.pending, (state) => {
        state.status = "loading";
        
      })
      .addCase(createOrder.fulfilled, (state, action) => {
        state.status = "succeeded";
        console.log(
          "createOrder Response payload in fulfilled case:",
          action.payload
        );
        console.log("State after fulfilled", state);
      })
      .addCase(createOrder.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("State after rejected", state);
      })

      .addCase(getAllOrder.pending, (state) => {
        state.status = "loading";
        
      })
      .addCase(getAllOrder.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.allOrders = action.payload?.data || [];
        
      })
      .addCase(getAllOrder.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("State after rejected", state);
      })

      .addCase(getAllReturnOrder.pending, (state) => {
        state.status = "loading";
       
      })
      .addCase(getAllReturnOrder.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.allReturnOrders = action.payload?.data || [];
        
      })
      .addCase(getAllReturnOrder.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("State after rejected", state);
      })

      .addCase(getAllCancelOrder.pending, (state) => {
        state.status = "loading";
        
      })
      .addCase(getAllCancelOrder.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.allCancelOrders = action.payload?.data || [];
        
      })
      .addCase(getAllCancelOrder.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("State after rejected", state);
      })

      .addCase(getOrder.pending, (state) => {
        state.status = "loading";
        
      })
      .addCase(getOrder.fulfilled, (state, action) => {
        state.status = "succeeded";
        console.log(
          "getOrder Response payload in fulfilled case:",
          action.payload
        );
        state.order = action.payload?.data || {};
        console.log("State after fulfilled", state);
      })
      .addCase(getOrder.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("State after rejected", state);
      })

      .addCase(getSingleReturnOrder.pending, (state) => {
        state.status = "loading";
       
      })
      .addCase(getSingleReturnOrder.fulfilled, (state, action) => {
        state.status = "succeeded";
        console.log(
          "getOrder Response payload in fulfilled case:",
          action.payload
        );
        state.returnOrder = action.payload?.data || {};
        console.log("State after fulfilled", state);
      })
      .addCase(getSingleReturnOrder.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("State after rejected", state);
      })

      .addCase(getSingleCancelOrder.pending, (state) => {
        state.status = "loading";
       
      })
      .addCase(getSingleCancelOrder.fulfilled, (state, action) => {
        state.status = "succeeded";
        console.log(
          "getOrder Response payload in fulfilled case:",
          action.payload
        );
        state.cancelOrder = action.payload?.data || {};
        console.log("State after fulfilled", state);
      })
      .addCase(getSingleCancelOrder.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("State after rejected", state);
      })

      .addCase(cancelOrder.pending, (state) => {
        state.status = "loading";
        
      })
      .addCase(cancelOrder.fulfilled, (state, action) => {
        state.status = "succeeded";
        console.log(
          "cancelOrder Response payload in fulfilled case:",
          action.payload.data
        );
        console.log("cancelOrder State after fulfilled", state);
      })
      .addCase(cancelOrder.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("State after rejected", state);
      })

      .addCase(returnOrder.pending, (state) => {
        state.status = "loading";
        
      })
      .addCase(returnOrder.fulfilled, (state, action) => {
        state.status = "succeeded";
        console.log(
          "returnOrder Response payload in fulfilled case:",
          action.payload.data
        );
        console.log("returnOrder State after fulfilled", state);
      })
      .addCase(returnOrder.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("State after rejected", state);
      })

      .addCase(createOrderAddress.pending, (state) => {
        state.status = "loading";
        
      })
      .addCase(createOrderAddress.fulfilled, (state, action) => {
        state.status = "succeeded";
        console.log(
          "createOrder Response payload in fulfilled case:",
          action.payload
        );
        console.log("State after fulfilled", state);
      })
      .addCase(createOrderAddress.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("State after rejected", state);
      })

      .addCase(getAllOrderAddress.pending, (state) => {
        state.status = "loading";
       
      })
      .addCase(getAllOrderAddress.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.allOrdersAddress = action.payload || [];
        
      })
      .addCase(getAllOrderAddress.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("State after rejected", state);
      })

      .addCase(getAllSippingOrderAddress.pending, (state) => {
        state.status = "loading";
        
      })
      .addCase(getAllSippingOrderAddress.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.allSppingOrdersAddress = action.payload || [];
       
      })
      .addCase(getAllSippingOrderAddress.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        
      })

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

      .addCase(deleteAddress.pending, (state) => {
        state.status = "loading";
       
      })
      .addCase(deleteAddress.fulfilled, (state, action) => {
        state.status = "succeeded";
        
      })
      .addCase(deleteAddress.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("postCartQuantity State after rejected", state);
      })
      .addCase(createOrderMessage.pending, (state) => {
        state.status = "loading";
       
      })
      .addCase(createOrderMessage.fulfilled, (state, action) => {
        state.status = "succeeded";
        
      })
      .addCase(createOrderMessage.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        
      })
      .addCase(getOrderMessage.pending, (state) => {
        state.status = "loading";
       
      })
      .addCase(getOrderMessage.fulfilled, (state, action) => {
        state.status = "succeeded";
        
        state.orderMessage = action.payload?.data || [];
        
      })
      .addCase(getOrderMessage.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
       
      })

      .addCase(CouponApplyed.pending, (state) =>
        handleAsyncState(state, { type: "pending" }, true)
      )
      .addCase(CouponApplyed.fulfilled, (state, action) =>
        handleAsyncState(
          state,
          { type: "fulfilled", payload: action.payload },
          true
        )
      )
      .addCase(CouponApplyed.rejected, (state, action) =>
        handleAsyncState(
          state,
          { type: "rejected", payload: action.payload },
          true
        )
      )

      .addCase(OrderCalculation.pending, (state) =>
        handleAsyncState(state, { type: "pending" }, true)
      )
      .addCase(OrderCalculation.fulfilled, (state, action) =>
        handleAsyncState(
          state,
          { type: "fulfilled", payload: action.payload },
          true
        )
      )
      .addCase(OrderCalculation.rejected, (state, action) =>
        handleAsyncState(
          state,
          { type: "rejected", payload: action.payload },
          true
        )
      );
    //   .addCase(getCoupons.pending, (state) => {
    //   state.status = "loading";
    //  
    // })
    // .addCase(getCoupons.fulfilled, (state, action) => {
    //   state.status = "succeeded";
    //   state.all_coupons = action.payload?.data || [];
    //   
    // })
    // .addCase(getCoupons.rejected, (state, action) => {
    //   state.status = "failed";
    //   state.error = action.payload;
    
    // })
  },
});

export default orderSlice.reducer;
