import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import Cookies from "js-cookie";
import { GET, PUT } 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 myaccountUpdate = createAsyncThunk(
  "common/auth/user-details-update",
  async (data, { rejectWithValue }) => {
    try {
      const response = await PUT(API.MY_ACCOUNT_UPDATE, data);

      if (response?.data?.success) {
        return response;
      }

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

export const B2bAccountUpdate = createAsyncThunk(
  "common/auth/b2b-user-details-update",
  async (data, { rejectWithValue }) => {
    try {
      const response = await PUT(API.B2b_ACCOUNT_UPDATE, data);

      if (response?.data?.success) {
        return response;
      }

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

// Thunk for getting Add banners
export const myAccount = createAsyncThunk(
  "common/auth/user-details",
  async (_, { rejectWithValue }) => {
    try {
      const myaccountData = await GET(API.MY_ACCOUNT);
      return myaccountData;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  },
);

export const profilephotoUpdate = createAsyncThunk(
  "common/auth/user-photo-update",
  async (data, { rejectWithValue }) => {
    try {
      const response = await PUT(API.MY_PHOTO_UPDATE, data);

      if (response?.success) {
        return response?.data;
      }

      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 Slice = createSlice({
  name: "myaccount",
  initialState: {
    token: "",
    name: "",
    addMyaccount: [],
    error: null,
    status: "idle",
  },
  reducers: {},
  extraReducers: (builder) => {
    builder

      .addCase(myaccountUpdate.pending, (state) =>
        handleAsyncState(state, { type: "pending" }),
      )
      .addCase(myaccountUpdate.fulfilled, (state, action) =>
        handleAsyncState(state, { type: "fulfilled", payload: action.payload }),
      )
      .addCase(myaccountUpdate.rejected, (state, action) =>
        handleAsyncState(state, { type: "rejected", payload: action.payload }),
      )

      .addCase(B2bAccountUpdate.pending, (state) =>
        handleAsyncState(state, { type: "pending" }),
      )
      .addCase(B2bAccountUpdate.fulfilled, (state, action) =>
        handleAsyncState(state, { type: "fulfilled", payload: action.payload }),
      )
      .addCase(B2bAccountUpdate.rejected, (state, action) =>
        handleAsyncState(state, { type: "rejected", payload: action.payload }),
      )

      .addCase(profilephotoUpdate.pending, (state) =>
        handleAsyncState(state, { type: "pending" }),
      )
      .addCase(profilephotoUpdate.fulfilled, (state, action) =>
        handleAsyncState(state, { type: "fulfilled", payload: action.payload }),
      )
      .addCase(profilephotoUpdate.rejected, (state, action) =>
        handleAsyncState(state, { type: "rejected", payload: action.payload }),
      )

      .addCase(myAccount.pending, (state) => {
        state.status = "loading";
      })
      .addCase(myAccount.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.addMyaccount = action.payload?.data || {};
      })
      .addCase(myAccount.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
      });
  },
});

export const { setIsSignedOut } = Slice.actions;

export default Slice.reducer;
