import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import API from "../../api";

const baseURL = process.env.NEXT_PUBLIC_BASE_URL_RETAILER;

export const getPriceCall = createAsyncThunk(
  "get/getPriceCall",
  async ({ width, height, category_id, pattern_id }: { width: number, height: number, category_id: number, pattern_id?: number }, thunkAPI) => {
    try {
      // Build URL based on whether pattern_id is provided
      const url = pattern_id 
        ? `${baseURL}/quotation/price_call/${width}/${height}/${category_id}/${pattern_id}`
        : `${baseURL}/quotation/price_call/${width}/${height}/${category_id}`;
      
      const response: any = await API.get(url);
      if (response.data === undefined || typeof response.data !== "object") {
        return thunkAPI.rejectWithValue("Invalid data received");
      }
      console.log(response, "api resp >>>>>")
      return response?.data;
    } catch (error: any) {
      const message =
        (error.response && error.response.data && error.response.data?.message) ||
        error.message ||
        error.toString();
      return thunkAPI.rejectWithValue(message);
    }
  }
);

interface priceCallState {
  isGetPriceCallSuccess: boolean;
  priceCallData: any | null;
  isGetPriceCallError: string | undefined;
  isGetPriceCallLoading: boolean;
}

const initialState: priceCallState = {
  isGetPriceCallSuccess: false,
  priceCallData: null,
  isGetPriceCallError: "",
  isGetPriceCallLoading: false
};

const priceCallSlice = createSlice({
  name: "priceCallSlice",
  initialState,
  reducers: {
    resetGetPriceCall: (state: priceCallState) => {
      state.isGetPriceCallSuccess = false;
      state.priceCallData = null;
      state.isGetPriceCallError = "";
      state.isGetPriceCallLoading = false;
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(getPriceCall.pending, (state: priceCallState) => {
        state.isGetPriceCallLoading = true;
        state.isGetPriceCallError = "";
        state.priceCallData = null;
        state.isGetPriceCallSuccess = false;
      })
      .addCase(
        getPriceCall.fulfilled,
        (state: priceCallState, action: ReturnType<typeof getPriceCall.fulfilled>) => {
          state.isGetPriceCallLoading = false;
          state.priceCallData = action?.payload?.priceCallData;
          state.isGetPriceCallSuccess = true;
          state.isGetPriceCallError = "";
        }
      )
      .addCase(getPriceCall.rejected, (state: priceCallState, action: any) => {
        state.isGetPriceCallLoading = false;
        state.isGetPriceCallError = action?.payload || "An error occurred";
        state.isGetPriceCallSuccess = false;
        state.priceCallData = null; // Reset data in case of rejection
      })
  },
});

export const { resetGetPriceCall } = priceCallSlice.actions;

export default priceCallSlice.reducer;

