import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import Cookies from "js-cookie";
import axiosInstanceClient from "@/utils/axiosClient";
import ShowAlertMixin from "@/shared/ShowAlertMixin";
interface CrudState {
  mainLoader: boolean;
  is_active: boolean;
  allNotificationsItems: any;
  notificationsMeta: any;
}

const initialState: CrudState = {
  mainLoader: true,
  allNotificationsItems: [],
  notificationsMeta: {},
  is_active: Cookies.get("courses_505_allow_notification")
    ? Cookies.get("courses_505_allow_notification") == "true"
    : true,
};

// Thunk for fetching items with pagination
export const getAllNotifications = createAsyncThunk(
  "notification/getAllNotifications",
  async ({ page }: { page: number }, { rejectWithValue }) => {
    try {
      const { data } = await axiosInstanceClient.get(`notifications`, {
        params: page,
      });
      return {
        notifications: data.data || [],
        meta: data.meta || {},
      };
    } catch (error: any) {
      rejectWithValue(error.message);
    }
  },
);

// Thunk for adding an item
export const toggleActiveNotification = createAsyncThunk(
  "notification/toggleActiveNotification",
  async (_, { rejectWithValue, dispatch }) => {
    try {
      const { data } = await axiosInstanceClient.post(`is_allow_notification`);
      if (data?.status === "success") {
        ShowAlertMixin({
          icon: "success",
          title: data?.message,
        });
        return data?.data?.is_allow_notification;
      }
    } catch (error: any) {
      return rejectWithValue(error.message);
    }
  },
);

// Slice
const notificationSlice = createSlice({
  name: "notification",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getAllNotifications.pending, (state) => {
        state.mainLoader = true;
      })
      .addCase(getAllNotifications.fulfilled, (state, action) => {
        state.mainLoader = false;
        state.allNotificationsItems = action.payload?.notifications;
        state.notificationsMeta = action.payload?.meta;
      })
      .addCase(getAllNotifications.rejected, (state) => {
        state.mainLoader = false;
      })
      .addCase(toggleActiveNotification.pending, (state) => {
        state.mainLoader = true;
      })
      .addCase(toggleActiveNotification.fulfilled, (state, action) => {
        state.mainLoader = false;
        state.is_active = action.payload;
        Cookies.set("courses_505_allow_notification", action.payload);
      })
      .addCase(toggleActiveNotification.rejected, (state) => {
        state.mainLoader = false;
      });
  },
});

export default notificationSlice.reducer;
