import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import Cookies from "js-cookie";
import { 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 contactusForm = createAsyncThunk(
  "website/contact",
  async (data, { rejectWithValue }) => {
    try {
      const response = await POST(API.CONTACT_US_FORM, 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);
    }
  },
);

// 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 contactusSlice = createSlice({
  name: "contactus",
  initialState: {
    name: "",
    email: "",
    number: "",
    message: "",
    token: "",
    name: "",
    error: null,
    status: "idle",
    is_signin: false,
  },
  reducers: {
    setIsSignedOut: (state) => {
      state.is_signin = false;
      state.token = "";
      state.name = "";
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(contactusForm.pending, (state) =>
        handleAsyncState(state, { type: "pending" }),
      )
      .addCase(contactusForm.fulfilled, (state, action) =>
        handleAsyncState(state, { type: "fulfilled", payload: action.payload }),
      )
      .addCase(contactusForm.rejected, (state, action) =>
        handleAsyncState(state, { type: "rejected", payload: action.payload }),
      );
  },
});

export const { setIsSignedOut } = contactusSlice.actions;

export default contactusSlice.reducer;
