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

const baseURL = process.env.NEXT_PUBLIC_BASE_URL_RETAILER;

export const getEditQuotation = createAsyncThunk(
  "get/getEditQuotation",
  async (id: string, thunkAPI) => {
    try {
      const response: any = await API.get(
        `${baseURL}/quotation/edit_quotation/${id}`
      );
      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 editQuoteState {
  isGetEditQuoteSuccess: boolean;
  isGetEditQuoteData: any | null;
  isGetEditQuoteError: string | undefined;
  isGetEditQuoteLoading: boolean;
}

const initialState: editQuoteState = {
  isGetEditQuoteSuccess: false,
  isGetEditQuoteData: null,
  isGetEditQuoteError: "",
  isGetEditQuoteLoading: false
};

const getEditQuotationSlice = createSlice({
  name: "getEditQuotationSlice",
  initialState,
  reducers: {
    resetGetEditQuote: (state: editQuoteState) => {
      state.isGetEditQuoteSuccess = false;
      state.isGetEditQuoteData = null;
      state.isGetEditQuoteError = "";
      state.isGetEditQuoteLoading = false;
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(getEditQuotation.pending, (state: editQuoteState) => {
        state.isGetEditQuoteLoading = true;
        state.isGetEditQuoteError = "";
        state.isGetEditQuoteData = null;
        state.isGetEditQuoteSuccess = false;
      })
      .addCase(
        getEditQuotation.fulfilled,
        (state: editQuoteState, action: ReturnType<typeof getEditQuotation.fulfilled>) => {
          state.isGetEditQuoteLoading = false;
          state.isGetEditQuoteData = action?.payload?.data;
          state.isGetEditQuoteSuccess = true;
          state.isGetEditQuoteError = "";
        }
      )
      .addCase(getEditQuotation.rejected, (state: editQuoteState, action: any) => {
        state.isGetEditQuoteLoading = false;
        state.isGetEditQuoteError = action?.payload || "An error occurred";
        state.isGetEditQuoteSuccess = false;
        state.isGetEditQuoteData = null; // Reset data in case of rejection
      })
  },
});

export const { resetGetEditQuote } = getEditQuotationSlice.actions;

export default getEditQuotationSlice.reducer;

