/*
 *
 * Create reducer
 *
 */

import { fromJS } from 'immutable';
import * as types from './constants';

export const initialState = fromJS({
  getAllTemplatesInProgress: false,
  fetchedOrgLevelCampaignSettings: true,
  templates: [],
  deleteResponse: {},
  deleteTemplateInProgress: false,
  deleteTemplateError: null,
  deleteRcsTemplateInProgress: false,
  deleteRcsTemplateError: null,
  deleteRcsResponse: {},
  templateError: {},
  campaignSettings: {
    messageSettings: {
      enableLinkTracking: false,
    },
    alertsSettings: {},
    reportsSettings: {},
  },
  senderDetails: {},
  archiveFilter: 'active',
  isArchivedMode: false,
  selectedTemplateIds: fromJS([]),
  archiveInProgress: false,
  unarchiveInProgress: false,
  bulkArchiveInProgress: false,
  bulkUnarchiveInProgress: false,
  archiveListingRefreshType: null,
});

function templatesReducer(state = initialState, action) {
  switch (action.type) {
    case types.DEFAULT_ACTION:
      return state;
    case types.GET_ALL_TEMPLATES_REQUEST:
      return state.set('getAllTemplatesInProgress', true).set('templateError', {});
    case types.GET_ALL_TEMPLATES_SUCCESS:
      if (action.isReset) {
        return state.set('getAllTemplatesInProgress', false)
          .set('archiveListingRefreshType', null)
          .set('templates', action.data ? action.data.templates : [])
          .set('isSearch', action.data ? action.data.search : false)
          .set('weCRMtemplates', action.weCRMTemplate ? action.weCRMTemplate : []).set('templateError', {});
      }
      return state.set('getAllTemplatesInProgress', false)
        .set('archiveListingRefreshType', null)
        .set('templates', action.data ? state.get('templates').concat(action.data.templates) : [])
        .set('isSearch', action.data ? action.data.search : false)
        .set('weCRMtemplates', action.weCRMTemplate ? state.get('weCRMtemplates').concat(action.weCRMTemplate) : []);
    case types.GET_ALL_TEMPLATES_FAILURE:
      return state.set('getAllTemplatesInProgress', false).set('archiveListingRefreshType', null).set('templateError', action.error);
    case types.DELETE_TEMPLATE_REQUEST:
      return state.set('deleteTemplateInProgress', true)
        .set('deleteTemplateError', null);
    case types.DELETE_TEMPLATE_SUCCESS:
      return state.set('deleteTemplateInProgress', false)
        .set('deleteResponse', action.data)
        .set('deleteTemplateError', null);
    case types.DELETE_TEMPLATE_FAILURE:
      return state.set('deleteTemplateInProgress', false)
        .set('deleteTemplateError', action.error);
    case types.DELETE_RCS_TEMPLATE_REQUEST:
      return state.set('deleteRcsTemplateInProgress', true)
        .set('deleteRcsTemplateError', null);
    case types.DELETE_RCS_TEMPLATE_SUCCESS:
      return state.set('deleteRcsTemplateInProgress', false)
        .set('deleteRcsResponse', action.data)
        .set('deleteRcsTemplateError', null);
    case types.DELETE_RCS_TEMPLATE_FAILURE:
      return state.set('deleteRcsTemplateInProgress', false)
        .set('deleteRcsTemplateError', action.error);
    case types.GET_USER_LIST_REQUEST:
      return state
        .set('fetchingUserList', true)
        .set('userList', fromJS({}))
        .set('userListFetchError', false);
    case types.GET_USER_LIST_SUCCESS:
      return state
        .set('fetchingUserList', false)
        .set('userList', fromJS(action.data))
        .set('userListFetchError', false);
    case types.GET_USER_LIST_FAILURE:
      return state
        .set('fetchingUserList', false)
        .set('userList', fromJS({}))
        .set('userListFetchError', true);
    case types.GET_WECRM_ACCOUNTS_REQUEST:
      return state
        .set('fetchingWeCrmAccounts', true)
        .set('weCrmAccountFetchingError', false)
        .remove('selectedWeChatAccount')
        .remove('weCrmAccounts');
    case types.GET_WECRM_ACCOUNTS_SUCCESS:
      return state
        .set('fetchingWeCrmAccounts', false)
        .set('weCrmAccounts', fromJS(action.data));
    case types.GET_WECRM_ACCOUNTS_FAILURE:
      return state
        .set('fetchingWeCrmAccounts', false)
        .set('weCrmAccountFetchingError', true);
    case types.SET_WECHAT_ACCOUNT:
      return state
        .set('selectedWeChatAccount', fromJS(action.weChatAccount))
        .set('templates', []);
    case types.SET_LINE_ACCOUNT:
      return state
        .set('selectedLineAccount', fromJS(action.account))
        .set('templates', []);
    case types.SET_VIBER_ACCOUNT:
      return state
        .set('selectedViberAccount', fromJS(action.viberAccount))
        .set('templates', []);
    case types.SET_WHATSAPP_ACCOUNT:
      return state
        .set('selectedWhatsappAccount', fromJS(action.account))
        .set('templates', []);
    case types.SET_ZALO_ACCOUNT:
      return state
        .set('selectedZaloAccount', fromJS(action.account))
        .set('templates', []);
    case types.SET_RCS_ACCOUNT:
      return state
        .set('selectedRcsAccount', fromJS(action.account))
        .set('templates', []);
    case types.SET_FACEBOOK_ACCOUNT:
      return state
        .set('selectedFacebookAccount', fromJS(action.faceBookAccount))
        .set('templates', []);
    case types.SET_WEBPUSH_ACCOUNT:
      return state
        .set('selectedWebPushAccount', fromJS(action.account))
        .set('templates', []);
    case types.RESET_ACCOUNT:
      return state
        .remove('selectedWeChatAccount')
        .remove('weCrmAccounts');
    case types.RESET_TEMPLATE:
      return state
        .set('weCRMtemplates', fromJS([]))
        .set('weChatDefaultTemplate', fromJS([]))
        .set('templates', []);
    case types.SET_SELECTED_LAYOUT:
      return state
        .set('selectedEmailLayout', fromJS(action.selectedTemplate))
        .set('edmTemplate', fromJS({}))
        .set('BEETemplate', fromJS({}));
    case types.RESET_UPLOAD_DATA:
      return state
        .set('selectedEmailLayout', "");
    case types.SEND_ZIPPED_FILE_REQUEST:
      return state
        .set('sendingFile', true)
        .set('errorSendingFile', false)
        .set('selectedEmailLayout', "");
    case types.SEND_ZIPPED_FILE_SUCCESS:
      return state
        .set('sendingFile', false)
        .set('selectedEmailLayout', fromJS(action.selectedTemplate))
        .set('edmTemplate', fromJS({}))
        .set('BEETemplate', fromJS({}));
    case types.SEND_ZIPPED_FILE_FAILURE:
      return state
        .set('sendingFile', false)
        .set('errorSendingFile', true)
        .set('errorMessage', action.data)
        .set('selectedEmailLayout', "");
    case types.GET_DEAFULT_BEE_TEMPLATES_REQUEST:
      return state.set('getCmsTemplatesInProgress', true);
    case types.GET_DEAFULT_BEE_TEMPLATES_SUCCESS:
      return state.set('getCmsTemplatesInProgress', false)
        .set('cmsTemplates', action.data ? fromJS(action.data.templates) : []);
    case types.GET_DEAFULT_BEE_TEMPLATES_FAILURE:
      return state.set('getCmsTemplatesInProgress', false);
    case types.SET_EDM_TEMPLATE:
      return state
        .set('edmTemplate', fromJS(action.template))
        .set('BEETemplate', fromJS(action.template))
        .set('selectedEmailLayout', "");
    case types.SET_BEE_TEMPLATE:
      return state
        .set('BEETemplate', fromJS(action.template))
        .set('selectedEmailLayout', "");
    case types.RESET_TEMPLATE_DATA:
      return state
        .set('edmTemplate', fromJS({}))
        .set('BEETemplate', fromJS({}))
        .set('selectedEmailLayout', "")
        .set('templateDetails', fromJS({}));
    case types.GET_TEMPLATE_DETAILS_REQUEST:
      return state
        .set('getTemplateDetailsInProgress', true)
        .set('templateDetails', fromJS({}));
    case types.GET_TEMPLATE_DETAILS_SUCCESS:
      return state
        .set('getTemplateDetailsInProgress', false)
        .set('templateDetails', fromJS(action.data));
    case types.GET_TEMPLATE_DETAILS_FAILURE:
      return state
        .set('getTemplateDetailsInProgress', false)
        .set('templateDetails', fromJS({}));
    case types.CLEAR_TEMPLATE_STORE_DATA:
      return state
        .set('templates', [])
        .set('weCRMtemplates', fromJS({}));
    case types.GET_ORG_LEVEL_CAMPAIGN_SETTINGS_REQUEST:
      return state.set('fetchedOrgLevelCampaignSettings', false);
    case types.GET_ORG_LEVEL_CAMPAIGN_SETTINGS_SUCCESS:
      return state.set('fetchedOrgLevelCampaignSettings', true).set(
        'campaignSettings',
        fromJS({
          ...state.get('campaignSettings'),
          ...(action.result || {}).entity,
        }),
      );
    case types.GET_ORG_LEVEL_CAMPAIGN_SETTINGS_FAILURE:
      return state.set('fetchedOrgLevelCampaignSettings', false);
    case types.GET_SENDER_DETAILS_REQUEST:
      return state.set('senderDetails', { status: 'REQUEST' });
    case types.GET_SENDER_DETAILS_SUCCESS: {
      const { channel, domainProperties = {} } = action?.payload || {};
      const isMultiAccountChannel = ['WHATSAPP', 'ZALO', 'RCS'].includes(channel);
      const senderDetailsKey = isMultiAccountChannel ? 'domainProperties' : 'hostName';
      // For Whatsapp, Zalo and RCS we need to store domainProperties instead of only hostName
      return state.set('senderDetails', {
        status: 'SUCCESS',
        [senderDetailsKey]: isMultiAccountChannel ? domainProperties : action?.payload,
        errors: [],
      });
    }
    case types.GET_SENDER_DETAILS_FAILURE:
      return state.set('senderDetails', {
        status: 'FAILURE',
        hostName: '',
        errors: action.payload,
      });
    case types.SET_ARCHIVE_FILTER:
      return state
        .set('archiveFilter', action.filter)
        .set('templates', [])
        .set('selectedTemplateIds', fromJS([]));
    case types.SET_ARCHIVED_MODE:
      return state
        .set('isArchivedMode', action.isArchived)
        .set('archiveFilter', action.isArchived ? 'archived' : 'active')
        .set('templates', [])
        .set('selectedTemplateIds', fromJS([]));
    case types.TOGGLE_TEMPLATE_SELECTION: {
      const rawSelected = state.get('selectedTemplateIds');
      // Defensive: handle undefined (stale persisted state) or plain array (pre-fromJS migration)
      const currentSelected = rawSelected && typeof rawSelected.toJS === 'function'
        ? rawSelected.toJS()
        : (Array.isArray(rawSelected) ? rawSelected : []);
      const idx = currentSelected.indexOf(action.id);
      const newSelected = idx === -1
        ? [...currentSelected, action.id]
        : currentSelected.filter((id) => id !== action.id);
      return state.set('selectedTemplateIds', fromJS(newSelected));
    }
    case types.SELECT_ALL_TEMPLATES:
      return state.set('selectedTemplateIds', fromJS(action.ids));
    case types.CLEAR_TEMPLATE_SELECTION:
      return state.set('selectedTemplateIds', fromJS([]));
    case types.ARCHIVE_TEMPLATE_REQUEST:
      return state.set('archiveInProgress', true).set('archiveError', null);
    case types.ARCHIVE_TEMPLATE_SUCCESS: {
      const afterArchive = state.get('selectedTemplateIds');
      const archiveSelected = afterArchive && typeof afterArchive.toJS === 'function' ? afterArchive.toJS() : [];
      return state
        .set('archiveInProgress', false)
        .set('archiveError', null)
        .set('archiveSuccessPayload', { successMessage: action.successMessage, description: action.description })
        .set('selectedTemplateIds', fromJS(archiveSelected.filter((sid) => sid !== action.id)));
    }
    case types.ARCHIVE_TEMPLATE_FAILURE:
      return state.set('archiveInProgress', false).set('archiveError', action.error);
    case types.UNARCHIVE_TEMPLATE_REQUEST:
      return state.set('unarchiveInProgress', true).set('unarchiveError', null);
    case types.UNARCHIVE_TEMPLATE_SUCCESS: {
      const afterUnarchive = state.get('selectedTemplateIds');
      const unarchiveSelected = afterUnarchive && typeof afterUnarchive.toJS === 'function' ? afterUnarchive.toJS() : [];
      return state
        .set('unarchiveInProgress', false)
        .set('unarchiveError', null)
        .set('unarchiveSuccessPayload', { successMessage: action.successMessage, description: action.description })
        .set('selectedTemplateIds', fromJS(unarchiveSelected.filter((sid) => sid !== action.id)));
    }
    case types.UNARCHIVE_TEMPLATE_FAILURE:
      return state.set('unarchiveInProgress', false).set('unarchiveError', action.error);
    case types.BULK_ARCHIVE_REQUEST:
      return state.set('bulkArchiveInProgress', true).set('bulkArchiveError', null);
    case types.BULK_ARCHIVE_SUCCESS:
      return state
        .set('bulkArchiveInProgress', false)
        .set('bulkArchiveError', null)
        .set('bulkArchiveSuccessPayload', { successMessage: action.successMessage, count: action.count })
        .set('selectedTemplateIds', fromJS([]));
    case types.BULK_ARCHIVE_FAILURE:
      return state.set('bulkArchiveInProgress', false).set('bulkArchiveError', action.error);
    case types.BULK_UNARCHIVE_REQUEST:
      return state.set('bulkUnarchiveInProgress', true).set('bulkUnarchiveError', null);
    case types.BULK_UNARCHIVE_SUCCESS:
      return state
        .set('bulkUnarchiveInProgress', false)
        .set('bulkUnarchiveError', null)
        .set('bulkUnarchiveSuccessPayload', { successMessage: action.successMessage, count: action.count })
        .set('selectedTemplateIds', fromJS([]));
    case types.BULK_UNARCHIVE_FAILURE:
      return state.set('bulkUnarchiveInProgress', false).set('bulkUnarchiveError', action.error);
    default:
      return state;
  }
}

export default templatesReducer;
