// src/store/crud.ts
import axiosInstance from '@/services/axiosClient';
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import toast from 'react-hot-toast';


interface AddItemProps {
    id: any;
    quantity?: number;
    setQuantity?: any;
    t?:any;
}

interface CrudState {
    mainLoader: boolean;
    allCartItems:any;
    openDeleteModal:boolean;
    openNotificationModal:boolean;
    priceDetails:any;
    itemId:number | null;
    cartLength:number;
    message:any;
    isSuccess: boolean;
    discount_code:any;
}

const initialState: CrudState = {
    mainLoader: false,
    allCartItems:[],
    priceDetails:{},
    openDeleteModal:false,
    openNotificationModal:false,
    itemId:null,
    cartLength:0,
    message:"",
    isSuccess:true,
    discount_code:null
};

// Thunk for fetching items with pagination
export const getAllCartItems = createAsyncThunk(
    'cart/getAllCartItems',
    async (_,{ rejectWithValue }) => {
        try {
            const { data } = await axiosInstance.get(`/cart`);
            return data || [];
        } catch (error: any) {
            return rejectWithValue(error.message);
        }
    }
);

// Thunk for adding an item
export const addProductToCart = createAsyncThunk(
  'cart/addProductToCart',
  async ({ id,quantity,t }: AddItemProps, { rejectWithValue }) => {
    try {
      const { data } = await axiosInstance.post(`/cart`,{
        product_detail_id:id,
        quantity:quantity
    });
    
    if (data?.status === "success") {
        toast.success(t("Messages.addToCartSuccessfully"));
        return  data
      }
    } catch (error: any) {
        toast.error(error.response?.data?.message);
        return rejectWithValue(error.response?.data?.message);
    }
  }
);

export const UpdateCartItem = createAsyncThunk(
  'cart/UpdateCartItem',
  async ({ id,quantity,setQuantity,t }: AddItemProps, { rejectWithValue,dispatch }) => {
    try {
      const { data } = await axiosInstance.patch(`/cart/${id}`,{
        quantity:quantity
    });
    if (data?.status === "success") {
        toast.success(t("Messages.updateSuccessfully"));
        return data
    }
} catch (error: any) {
    if(error.response?.data?.message == "Requested quantity exceeds available stock."){
        setQuantity((prev:any) => prev - 1)
    }
    toast.error(error.response?.data?.message);
    return rejectWithValue(error.response?.data?.message);
    }
  }
);

export const ApplyCoupon = createAsyncThunk(
  'cart/ApplyCoupon',
  async ({ code }: {code:string}, { rejectWithValue,dispatch }) => {
    try {
      const { data } = await axiosInstance.get(`/cart`,{ params:{code:code}});
      if (data?.coupon_status_code == 200) {
        toast.success(data.message);
        return {...data,code}
    }else{
        toast.error(data.message);
        return {...data}
    }
} catch (error: any) {
    toast.error(error.response?.data?.message);
    return rejectWithValue(error.response?.data?.message);
    }
  }
);

export const removeProductFromCart = createAsyncThunk(
  'cart/removeProductFromCart',
  async ({ id }: AddItemProps, { rejectWithValue,dispatch }) => {
    try {
      const { data } = await axiosInstance.delete(`/cart/${id}`);
      if (data?.status === "success") {
        toast.success(data?.message);
        dispatch(getAllCartItems());
        // return id
      }
    } catch (error: any) {
        // toast.error(error.response?.data?.message);
        return rejectWithValue(error.response?.data?.message);
    }
  }
);

// Slice
const cartSlice = createSlice({
    name: 'cart',
    initialState,
    reducers: { 
        setCouponCode : (state,action)=>{
            state.discount_code = action.payload
        }
    },
    extraReducers: (builder) => {
        builder
            .addCase(getAllCartItems.pending, (state) => {
                state.mainLoader = true;
            })
            .addCase(getAllCartItems.fulfilled,(state,action) => {
                state.mainLoader = false;
                state.allCartItems = action.payload?.data;
                state.cartLength = action.payload?.products || 0;
                state.priceDetails = {
                    subTotal: action.payload?.subTotal,
                    vat: action.payload?.vat,
                    vat_amount: action.payload?.vat_amount,
                    total: action.payload?.total,
                    discount_type: action.payload?.discount_type,
                    discount: action.payload?.discount,
                    discount_amount:action.payload?.discount_amount,
                    shipping_cost:action.payload?.shipping_cost
                } 
            })
            .addCase(getAllCartItems.rejected, (state) => {
                state.mainLoader = false;
            })
            .addCase(addProductToCart.pending, (state) => {
                state.mainLoader = true;
            })
            .addCase(addProductToCart.fulfilled, (state, action) => {
                state.mainLoader = false;
                state.allCartItems = action.payload?.data
                state.cartLength = action.payload?.products || 0
                state.priceDetails = {
                    subTotal: action.payload?.subTotal,
                    vat: action.payload?.vat,
                    vat_amount: action.payload?.vat_amount,
                    total: action.payload?.total,
                    discount_type: action.payload?.discount_type,
                    discount: action.payload?.discount,
                    discount_amount:action.payload?.discount_amount,
                    shipping_cost:action.payload?.shipping_cost
                } 
            })
            .addCase(addProductToCart.rejected, (state,action) => {
                state.mainLoader = false;
            })
            .addCase(UpdateCartItem.pending, (state) => {
                state.mainLoader = true;
            })
            .addCase(UpdateCartItem.fulfilled, (state, action) => {
                state.mainLoader = false;
                state.allCartItems = action.payload?.data
                state.cartLength = action.payload?.products || 0
                state.priceDetails = {
                    subTotal: action.payload?.subTotal,
                    vat: action.payload?.vat,
                    vat_amount: action.payload?.vat_amount,
                    total: action.payload?.total,
                    discount_type: action.payload?.discount_type,
                    discount: action.payload?.discount,
                    discount_amount:action.payload?.discount_amount,
                    shipping_cost:action.payload?.shipping_cost
                } 
            })
            .addCase(UpdateCartItem.rejected, (state,action) => {
                state.mainLoader = false;
            })
            .addCase(removeProductFromCart.pending, (state) => {
                state.mainLoader = true;
            })
            .addCase(removeProductFromCart.fulfilled, (state, action: any) => {
                state.mainLoader = false;
                // state.allCartItems = state.allCartItems.filter((item:any) => item.id !== action.payload);
                // state.cartLength = state.allCartItems.length;
                // state.priceDetails = {
                //     subTotal: action.payload?.subTotal,
                //     vat: action.payload?.vat,
                //     vat_amount: action.payload?.vat_amount,
                //     total: action.payload?.total,
                //     discount_type: action.payload?.discount_type,
                //     discount: action.payload?.discount,
                //     shipping_cost: action.payload?.shipping_cost
                // };
            })
            .addCase(removeProductFromCart.rejected, (state,action) => {
                state.mainLoader = false;
            })
            .addCase(ApplyCoupon.pending, (state) => {
                state.mainLoader = true;
            })
            .addCase(ApplyCoupon.fulfilled, (state, action : any) => {
                console.log("🚀 ~ .addCase ~ action.payload:", action.payload)
                state.mainLoader = false;
                state.allCartItems = action.payload?.data
                state.cartLength = action.payload?.products || 0
                state.priceDetails = {
                    subTotal: action.payload?.subTotal,
                    vat: action.payload?.vat,
                    vat_amount: action.payload?.vat_amount,
                    total: action.payload?.total,
                    discount_type: action.payload?.discount_type,
                    discount: action.payload?.discount,
                    discount_amount:action.payload?.discount_amount,
                    shipping_cost:action.payload?.shipping_cost
                }
                state.discount_code = action.payload?.code
            })
            .addCase(ApplyCoupon.rejected, (state,action) => {
                state.mainLoader = false;
            })
    },
});

export const { setCouponCode } = cartSlice.actions;

export default cartSlice.reducer;
