import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import Cookies from "js-cookie";
import { GET, POST } from "../../utils/api";
import { API } from "../../endpoints/common_endpoints";

// Utility function for API requests
const apiRequest = async (apiFn, api, data, errorMessage) => {
  try {
    const response = await apiFn(api, data);
    if (response?.success) {
      return response?.data;
    } else {
      throw new Error(response?.message || errorMessage);
    }
  } catch (error) {
    throw new Error(error.message || errorMessage);
  }
};

export const reviewPost = createAsyncThunk(
  "website/review",
  async (data, { rejectWithValue }) => {
    try {
      
      const response = await POST(API.REVIEW_RATING, data);
      if (response?.data?.token) {
        Cookies.set("shreeram_agro_security", response?.data?.token);
        return response?.data?.token;
      }

      return rejectWithValue(response);
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const AvgReviewRating = createAsyncThunk(
  "get-review-rating",
  async ({ product_id }, { rejectWithValue }) => {
    try {
      const termsconditionsData = await GET(
        `${API.AVG_REVIEW_RATING}/${product_id}`
      );
      return termsconditionsData;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const allReviewRating = createAsyncThunk(
  "al-review-rating",
  async ({ product_id,page }, { rejectWithValue }) => {
    try {
      const termsconditionsData = await GET(`${API.REVIEW_RATING}/${product_id}?page=${page}`);
      return termsconditionsData;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

// Helper function to handle common async state transitions
const handleAsyncState = (state, action, isSignin = false) => {
  switch (action.type) {
    case "pending":
      state.status = "loading";
      break;
    case "fulfilled":
      state.status = "succeeded";
      if (isSignin) {
        state.token = action.payload;
        state.is_signin = true;
      }
      break;
    case "rejected":
      state.status = "failed";
      state.error = action.payload;
      if (isSignin) state.is_signin = false;
      break;
    default:
      return state;
  }
};

// Create the slice
const careerformSlice = createSlice({
  name: "reviewRating",
  initialState: {
    token: "",
    name: "",
    avg_rating: "",
    all_rating: "",
    error: null,
    status: "idle",
    is_signin: false,
  },
  reducers: {
    setIsSignedOut: (state) => {
      state.is_signin = false;
      state.token = "";
      state.name = "";
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(reviewPost.pending, (state) =>
        handleAsyncState(state, { type: "pending" })
      )
      .addCase(reviewPost.fulfilled, (state, action) =>
        handleAsyncState(state, { type: "fulfilled", payload: action.payload })
      )
      .addCase(reviewPost.rejected, (state, action) =>
        handleAsyncState(state, { type: "rejected", payload: action.payload })
      )

      .addCase(AvgReviewRating.pending, (state) => {
        state.status = "loading";
       
      })
      .addCase(AvgReviewRating.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.avg_rating = action.payload?.data || [];
        console.log("State after fulfilled", state);
      })
      .addCase(AvgReviewRating.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("State after rejected", state);
      })

      .addCase(allReviewRating.pending, (state) => {
        state.status = "loading";
        
      })
      .addCase(allReviewRating.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.all_rating = action.payload?.data || [];
        console.log("State after fulfilled", state);
      })
      .addCase(allReviewRating.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
        console.log("State after rejected", state);
      });
  },
});

export const { setIsSignedOut } = careerformSlice.actions;

export default careerformSlice.reducer;
