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

import { SORT_DESC } from '@/modules/@common/constants/sort';

const initialState = {
  // common
  isLoading: false,
  players: [],
  publishers: [],
  publisher: null,
  fallbackOnly: false,
  search: '',
  page: 1,
  pageSize: 10,
  recordsTotal: 0,
  sortBy: 'Date',
  sortOrder: SORT_DESC,
  status: null,
  mode: null,
  aiPlaylistMode: false,

  playlists: [],
  // example of state.playlists:
  // playlists: [{
  //   // ...playlistInfo
  //   videos: [],
  //   aiPlaylists: {
  //     // { [$TYPE]: { id, length, type, filters: { id, videoFilterValues: [] } } }
  //     RECENT: null,
  //     TRENDING: null,
  //   },
  // }],
  playlistId: null,

  embedCodePopup: {
    playlistId: null,
    aspectRatio: null,
    player: null,
    embedCode: '',
  },
};

export const slice = createSlice({
  name: '@@EDITORIAL/SIDEBAR/PLAYLISTS',
  initialState,

  reducers: {
    // common
    setIsLoadingAction: (state, action) => {
      state.isLoading = action.payload;
    },
    getPlayersAction: (state) => state,
    setPlayersAction: (state, action) => {
      state.players = action.payload;
    },
    getPublishersAction: (state) => state,
    setPublishersAction: (state, action) => {
      state.publishers = action.payload;
    },
    setPublisherAction: (state, action) => {
      state.publisher = action.payload;
    },
    setFallbackOnlyAction: (state, action) => {
      state.fallbackOnly = action.payload;
    },
    searchPlaylistAction: (state, action) => {
      state.search = action.payload;
    },
    setPageAction: (state, action) => {
      state.page = action.payload;
    },
    setRecordsTotalAction: (state, action) => {
      state.recordsTotal = action.payload;
    },
    setSortByAction: (state, action) => {
      state.sortBy = action.payload;
    },
    setSortOrderAction: (state, action) => {
      state.sortOrder = action.payload;
    },
    setStatusAction: (state, action) => {
      state.status = action.payload;
    },
    setModeAction: (state, action) => {
      state.mode = action.payload;
    },
    setAiPlaylistModeAction: (state, action) => {
      state.aiPlaylistMode = action.payload;
    },

    // playlists
    getPlaylistsAction: (state) => state,
    setPlaylistsAction: (state, action) => {
      state.playlists = action.payload;
    },
    setPlaylistIdAction: (state, action) => {
      state.playlistId = action.payload;
    },
    getPlaylistByIdAction: (state) => state,
    updatePlaylistAction: (state, action) => {
      const playlistId = action.payload?.playlistId || state.playlistId;
      const playlist = state.playlists.find((playlist$) => playlist$.id === playlistId);

      if (playlist) {
        Object.keys(action.payload).forEach((key) => {
          playlist[key] = action.payload[key];
        });
      }
    },
    deletePlaylistAction: (state) => state,

    // videos
    getPlaylistVideosAction: (state) => state,
    setPlaylistVideosAction: (state, action) => {
      const { playlistId, videos } = action.payload;
      const playlist = state.playlists.find((playlist$) => playlist$.id === playlistId);

      if (playlist) {
        playlist.videos = videos;
      }
    },
    setPlaylistVideosAttributeAction: (state, action) => {
      const { uid, attribute } = action.payload;
      const playlist = state.playlists.find((playlist$) => playlist$.id === state.playlistId);

      if (playlist) {
        playlist.videos = playlist.videos.map((video) => (video.uid === uid ? { ...video, ...attribute } : video));
      }
    },
    searchVideoAction: (state) => state,

    // aiPlaylist
    getAiPlaylistAction: (state) => state,
    setAiPlaylistAction: (state, action) => {
      const { playlistId, aiPlaylist } = action.payload;

      const playlist = state.playlists.find((playlist$) => playlist$.id === playlistId);
      if (playlist) {
        if (!playlist.aiPlaylists) {
          playlist.aiPlaylists = {};
        }

        playlist.aiPlaylists[aiPlaylist.type] = aiPlaylist;
      }
    },
    createAiPlaylistAction: (state) => state,
    updateAiPlaylistAction: (state) => state,
    deleteAiPlaylistAction: (state, action) => {
      const { playlistId, aiPlaylistId } = action.payload;

      const playlist = state.playlists.find((playlist$) => playlist$.id === playlistId);

      if (playlist) {
        const aiPlaylist = Object.values(playlist.aiPlaylists).find((aiPlaylist$) => aiPlaylist$.id === aiPlaylistId);
        if (aiPlaylist) {
          delete playlist.aiPlaylists[aiPlaylist.type];
        }

        const aiPlaylistIdString = aiPlaylistId.toString();
        playlist.videos = playlist.videos.filter((video) => video.distributionId.toString() !== aiPlaylistIdString);
        playlist.clips = playlist.clips.filter((clip) => clip.toString() !== aiPlaylistIdString);
      }
    },

    // aiFilters
    getAiFiltersAction: (state) => state,
    setAiFiltersAction: (state, action) => {
      const { playlistId, aiPlaylistId, aiFilters } = action.payload;

      const playlist = state.playlists.find((playlist$) => playlist$.id === playlistId);

      if (playlist) {
        const aiPlaylist = Object.values(playlist.aiPlaylists).find((aiPlaylist$) => aiPlaylist$.id === aiPlaylistId);

        if (aiPlaylist) {
          if (!aiFilters || !aiFilters.length) {
            delete aiPlaylist.aiFilters;
          } else {
            aiPlaylist.aiFilters = aiFilters;
          }
        }
      }
    },
    updateAiFiltersAction: (state) => state,

    // embed code
    getEmbedCodeAction: (state) => state,
    getEmbedCodeSuccessAction: (state, action) => {
      state.embedCodePopup.embedCode = action.payload;
    },
    setEmbedCodeInfoAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state.embedCodePopup[key] = action.payload[key];
      });
    },
  },
});

export const {
  // common
  setIsLoadingAction,
  getPlayersAction,
  setPlayersAction,
  getPublishersAction,
  setPublishersAction,
  setPublisherAction,
  setFallbackOnlyAction,
  searchPlaylistAction,
  setPageAction,
  setRecordsTotalAction,
  setSortByAction,
  setSortOrderAction,
  setStatusAction,
  setModeAction,
  setAiPlaylistModeAction,
  // playlists
  getPlaylistsAction,
  setPlaylistsAction,
  setPlaylistIdAction,
  getPlaylistByIdAction,
  updatePlaylistAction,
  deletePlaylistAction,
  // videos
  getPlaylistVideosAction,
  setPlaylistVideosAction,
  searchVideoAction,
  setPlaylistVideosAttributeAction,
  // aiPlaylist
  getAiPlaylistAction,
  setAiPlaylistAction,
  createAiPlaylistAction,
  updateAiPlaylistAction,
  deleteAiPlaylistAction,
  // aiFilters
  getAiFiltersAction,
  setAiFiltersAction,
  updateAiFiltersAction,
  // embed code
  getEmbedCodeAction,
  getEmbedCodeSuccessAction,
  setEmbedCodeInfoAction,
} = slice.actions;

export default slice.reducer;
