import { createSlice } from "@reduxjs/toolkit";

export const gallerySlice = createSlice({
  name: "gallery",
  initialState: {
    gallery: [],
    page: null,
  },
  reducers: {
    setGallery: (state, action) => {
      state.gallery = action.payload;
    },

    setPage: (state, action) => {
      state.page = action.payload;
    },

    addGalleryItem: (state, action) => {
      const gallery = Array.isArray(action.payload.data)
        ? action.payload.data
        : [action.payload.data];
      const page = action.payload.page;

      state.gallery.push(...gallery);
      state.page = page;
    },

    editGalleryData: (state, action) => {
      const currentIndex = state.gallery.findIndex(
        (gallery) => gallery.id === action.payload._id
      );

      if (currentIndex !== -1) state.gallery[currentIndex] = action.payload;
    },

    deleteGalleryOnIndex: (state, action) => {
      const currentData = state.gallery?.[action.payload.index];
      if (!currentData) return;

      state.gallery = state.gallery.filter(
        (_, index) => index !== action.payload.index
      );
    },
  },
  selectors: {
    selectGallery: (state) => state.gallery,
    selectPageGallery: (state) => state.page,
  },
});

export const {
  addGalleryItem,
  deleteGalleryOnIndex,
  setGallery,
  editGalleryData,
} = gallerySlice.actions;
export const { selectGallery, selectPageGallery } = gallerySlice.selectors;

export default gallerySlice.reducer;
