import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import CartService from '../../services/CartService';

const initialState = {
  cart: {},
  status: null,
  error: null,
};

export const createCart = createAsyncThunk(
  'cart/createCart',
  async () => {
    const response = await CartService.createCart();
    return response;
  }
);

export const fetchCart = createAsyncThunk(
  'cart/fetchCart',
  async (cartId, { rejectWithValue }) => {
    try {
      const response = await CartService.getCart(cartId);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const addItemToCart = createAsyncThunk(
  'cart/addItemToCart',
  async ({ cartId, lines }, { rejectWithValue }) => {
    try {
      const response = await CartService.addItemToCart(cartId, lines);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const updateItemQuantity = createAsyncThunk(
  'cart/updateItemQuantity',
  async ({ cartId, lineId, quantity }, { rejectWithValue }) => {
    try {
      const response = await CartService.updateItemQuantity(cartId, lineId, quantity);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const fetchCheckoutUrl = createAsyncThunk(
  'cart/fetchCheckoutUrl',
  async (cartId, { rejectWithValue }) => {
    try {
      const response = await CartService.getCheckoutUrl(cartId);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

// Slice
export const cartSlice = createSlice({
  name: 'cart',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      // Create Cart
      .addCase(createCart.pending, (state) => {
        state.status = 'loading';
        state.error = null;
      })
      .addCase(createCart.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.cart = action.payload;
        localStorage.setItem('amber-cart', JSON.stringify(action.payload));
      })
      .addCase(createCart.rejected, (state, action) => {
        state.status = 'failed';
        state.cart = {};
        state.error = action.payload || action.error.message;
      })

      // Add Item to Cart
      .addCase(addItemToCart.pending, (state) => {
        state.status = 'loading';
        state.error = null;
      })
      .addCase(addItemToCart.fulfilled, (state, action) => {
        state.status = 'succeeded';
        localStorage.setItem('amber-cart', JSON.stringify(action.payload));
        state.cart = action.payload;
      })
      .addCase(addItemToCart.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.payload || action.error.message;
      })

      // Fetch Cart
      .addCase(fetchCart.pending, (state) => {
        state.status = 'loading';
        state.error = null;
      })
      .addCase(fetchCart.fulfilled, (state, action) => {
        state.status = 'succeeded';
        if(action.payload) localStorage.setItem('amber-cart', JSON.stringify(action.payload))
        else localStorage.removeItem('amber-cart')
        
        state.cart = action.payload;
      })
      .addCase(fetchCart.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.payload || action.error.message;
      })

      // Update Item Quantity
      .addCase(updateItemQuantity.pending, (state) => {
        state.status = 'loading';
        state.error = null;
      })
      .addCase(updateItemQuantity.fulfilled, (state, action) => {
        state.status = 'succeeded';
        localStorage.setItem('amber-cart', JSON.stringify(action.payload));
        state.cart = action.payload;
      })
      .addCase(updateItemQuantity.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.payload || action.error.message;
      })

      // Fetch Checkout URL
      .addCase(fetchCheckoutUrl.pending, (state) => {
        state.status = 'loading';
        state.error = null;
      })
      .addCase(fetchCheckoutUrl.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.cart.checkoutUrl = action.payload; // Only update checkout URL
      })
      .addCase(fetchCheckoutUrl.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.payload || action.error.message;
      });
  },
});

export default cartSlice.reducer;
