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

import {
  ALL_TYPE,
  ASPECT_RATIOS,
  PLAYER_TYPES,
  ROWS_PER_PAGE_DEFAULT,
  TABLE_HEADER,
  TABLE_REDUX_FIELD_NAME,
} from '../../constants';
import { SORT_ASC } from '@/modules/@common/constants/sort';

import createTableSlice from '@/modules/@common/Table/redux/slices';

const tableSlice = createTableSlice(TABLE_REDUX_FIELD_NAME, {
  pageSize: ROWS_PER_PAGE_DEFAULT,
  sortBy: TABLE_HEADER.find((column) => column.isDefaultSortBy)?.id || 'id',
  sortOrder: TABLE_HEADER.find((column) => column.isDefaultSortBy)?.defaultSortOrder || SORT_ASC,
});

const addDataARToEmbedCode = (embedCodeText, dataARValue) => {
  const existingDataAR = embedCodeText.match(/data-ar\s*=\s*['"]([^'"]+)['"]/);
  let embedCode;

  if (existingDataAR) {
    embedCode = embedCodeText.replace(existingDataAR[0], `data-ar="${dataARValue}"`);
  } else {
    embedCode = embedCodeText.replace(/(src\s*=\s*['"]([^'"]+)['"])/i, `$1 data-ar="${dataARValue}"`);
  }

  return embedCode;
};

const handleChangeEmbedCodeSrc = (embedCodeText, src) => {
  if (src) {
    return embedCodeText.replace(/src="([^"]*)"/, `src="${src}"`);
  }
  return embedCodeText;
};

const initialState = {
  /// TABLE ///
  ...tableSlice.state,

  /// FILTERS ///
  search: '',
  publisher: null,
  publishersOptions: [],
  type: ALL_TYPE,
  typesOptions: [],

  /// ROW ACTIONS ///
  embedCode: '',
  aspectRatio: ASPECT_RATIOS[0],
  embedSources: null,

  /// ADDITION ///
  newPlayerType: {},
  allRecordsCount: 0,
};

export const slice = createSlice({
  name: '@@PLAYER/LIST',
  initialState,

  reducers: {
    getDataAction: tableSlice.actions.getTableDataAction,
    setTableAction: tableSlice.actions.setTableAction,
    setAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state[key] = action.payload[key];
      });
    },
    getUiPropsAction: (state) => state,
    getPublishersOptionsAction: (state) => state,
    setEmbedCodeAction: (state, { payload }) => {
      const player = state[TABLE_REDUX_FIELD_NAME].data.find((row) => row.id === payload.id);
      const hasEmbedCodeAspectRatio =
        PLAYER_TYPES.find((p) => p.id === player.type)?.embedCodeAspectRatio && player.embedCode;
      if (hasEmbedCodeAspectRatio) {
        state.embedCode = addDataARToEmbedCode(player.embedCode, state.aspectRatio.label);
      } else {
        state.embedCode = player.embedCode || '';
      }
    },
    setEmbedCodeByTypeAction: (state, { payload }) => {
      const player = state[TABLE_REDUX_FIELD_NAME].data.find((row) => row.id === payload.id);
      const hasEmbedCodeTypes = PLAYER_TYPES.find((p) => p.id === player.type)?.embedCodeTypes && player.embedCode;

      state.embedCode = hasEmbedCodeTypes
        ? handleChangeEmbedCodeSrc(player.embedCode, state.embedSources[payload.embedCodeTypeObj.value])
        : player.embedCode || '';
    },
    setAspectRatio: (state, { payload }) => {
      state.aspectRatio = payload.aspectRatioObj;
      const player = state[TABLE_REDUX_FIELD_NAME].data.find((row) => row.id === payload.id);
      const hasEmbedCodeAspectRatio = PLAYER_TYPES.find((p) => p.id === player.type)?.embedCodeAspectRatio;
      if (hasEmbedCodeAspectRatio) {
        state.embedCode = addDataARToEmbedCode(state.embedCode, payload.aspectRatioObj.label);
      }
    },

    deletePlayerAction: (state) => state,
  },
});

export const {
  getDataAction,
  setTableAction,
  setAction,
  getPublishersOptionsAction,
  getUiPropsAction,
  setEmbedCodeAction,
  setAspectRatio,
  deletePlayerAction,
  setEmbedCodeByTypeAction,
} = slice.actions;
