import { createSlice } from "@reduxjs/toolkit";
import { cartReset, customerOrderDetail, orderDetailReset, removeCartItem, updateAddress, updateCart, updateCartItem } from "../../actions/user/userAction";

interface InitialState {
  cartItems: any;
  orderDetail: any;
  profileDetail: any;
  success: boolean;
  loading: boolean;
  error: any;
  selectedAddress: any;
}

const initialState: InitialState = {
  profileDetail: null,
  orderDetail: null,
  cartItems: [],
  loading: false,
  success: false,
  error: null,
  selectedAddress: null,
};

const profileSlice = createSlice({
  name: "profile",
  initialState: initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(updateCart.fulfilled, (state, action) => {
        state.cartItems = [
          ...state.cartItems.filter(
            (existing: any) =>
              !action.payload.some(
                (incoming: any) => incoming._id === existing._id
              )
          ),
          ...action.payload,
        ];
      })
      .addCase(updateCartItem.fulfilled, (state, action) => {
        const updatedItem = action.payload;
        const index = state.cartItems.findIndex(
          (item: any) => {
            if (updatedItem.cart_item_key && item.cart_item_key) {
              return item.cart_item_key === updatedItem.cart_item_key;
            }
            return item.food_id === updatedItem.food_id;
          }
        );
        if (index !== -1) {
          state.cartItems[index] = {
            ...state.cartItems[index],
            ...updatedItem,
          };
        }
      })
      .addCase(removeCartItem.fulfilled, (state, action) => {
        const updatedItem = action.payload; // This is the payload, which could be cartItemKey or food_id
        state.cartItems = state.cartItems.filter(
          (item: any) => {
            if (item.cart_item_key && item.cart_item_key === updatedItem) {
              return false;
            }
            if (item.food_id === updatedItem) {
              return false;
            }
            return true;
          }
        );
      })
      .addCase(customerOrderDetail.fulfilled, (state, action) => {
        const updatedItem = action.payload;
        const newOrderDetail = {
          ...state.orderDetail,
          ...updatedItem,
        };

        // Ensure cart_items and other_cart_items are mutually exclusive
        if (updatedItem.cart_items) {
          delete newOrderDetail.other_cart_items;
        } else if (updatedItem.other_cart_items) {
          delete newOrderDetail.cart_items;
        }

        state.orderDetail = newOrderDetail;
      })
      .addCase(orderDetailReset, (state) => {
        state.orderDetail = null;
      })
      .addCase(cartReset, (state) => {
        state.cartItems = [];
      })
      .addCase(updateAddress.fulfilled, (state, action) => {
        state.selectedAddress = action.payload;
      });
  },
});

export const profileReducer = profileSlice.reducer;
