import axiosInstanceClient from "@/utils/axiosClient";
import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";

interface CartItem {
  id: number;
  amount: number;
  product: any;
}

interface CartState {
  items: CartItem[];
  totalPrice: number;
  subTotal: number;
  productCount: number;
  shipping_price: number;
  tax_amount: number;
  error: { status: number | null };
  mainLoader: boolean;
}

const initialState: CartState = {
  items: [],
  totalPrice: 0,
  subTotal: 0,
  productCount: 0,
  shipping_price: 0,
  tax_amount: 0,
  error: { status: null },
  mainLoader: true,
};

export const getAllCartItems = createAsyncThunk(
  "cart/getAllCartItems",
  async (_, { rejectWithValue }) => {
    try {
      const { data } = await axiosInstanceClient.get("client/carts");
      return data || [];
    } catch (error: any) {
      return rejectWithValue({ status: error.response?.status || 404 });
    }
  },
);

const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addItem: (state, action: PayloadAction<CartItem>) => {
      const { id, product, amount } = action.payload;
      const idx = state.items.findIndex((item) => item.id === id);
      const item = state.items[idx];
      if (idx >= 0) {
        item.amount += 1;
        state.totalPrice = Number(
          (+state.totalPrice + +product.price).toFixed(2),
        );
      } else {
        state.items.push({ ...action.payload, amount: amount });
        state.productCount += 1;
        state.totalPrice = Number(
          (+state.totalPrice + +product.price * amount).toFixed(2),
        );
      }

      state.subTotal = state.totalPrice;
    },
    removeItem: (state, action: PayloadAction<{ id: number }>) => {
      const { id } = action.payload;
      const idx = state.items.findIndex((item) => item.id === id);
      const item = state.items[idx];
      if (idx >= 0) {
        state.totalPrice = Number(
          (+state.totalPrice - +item.product.price * +item.amount).toFixed(2),
        );
        state.items.splice(idx, 1);
        state.productCount -= 1;
      }
      state.subTotal = state.totalPrice;
    },
    decreaseItemQuantity: (state, action: PayloadAction<{ id: number }>) => {
      const { id } = action.payload;
      const idx = state.items.findIndex((item) => item.id === id);
      const item = state.items[idx];
      if (idx >= 0 && +item.amount > 1) {
        item.amount -= 1;
        state.totalPrice = Number(
          (+state.totalPrice - +item.product.price).toFixed(2),
        );
      }
      state.subTotal = state.totalPrice;
    },
    setProductCount: (state, action: PayloadAction<number>) => {
      state.productCount = action.payload;
    },
    clearCart: (state) => {
      state.items = [];
      state.totalPrice = 0;
      state.productCount = 0;
      state.subTotal = 0;
      state.shipping_price = 0;
      state.error = { status: null };
      state.mainLoader = false;
    },
    setShippingPrice: (state, action: PayloadAction<number>) => {
      state.shipping_price = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(getAllCartItems.pending, (state) => {
        state.mainLoader = true;
      })
      .addCase(getAllCartItems.fulfilled, (state, action) => {
        state.items = [];
        const payload = action.payload?.data[0];
        payload?.items?.length > 0
          ? payload?.items?.map((item: any) => {
              state.items.push({
                id: item?.id,
                ...item,
                amount: +item?.amount,
              });
            })
          : (state.items = []);
        state.productCount = payload?.items?.length || 0;
        // state.totalPrice = +payload?.total - payload?.shipping_price;
        state.totalPrice = +payload?.total_price;
        state.subTotal = +payload?.price;
        state.shipping_price = +payload?.shipping_price;
        state.tax_amount = +payload?.tax_amount;
        state.mainLoader = false;
      })
      .addCase(getAllCartItems.rejected, (state) => {
        state.mainLoader = false;
      });
  },
});

export const {
  addItem,
  removeItem,
  decreaseItemQuantity,
  setProductCount,
  setShippingPrice,
  clearCart,
} = cartSlice.actions;

export default cartSlice.reducer;
