/**
 * Customer Search Section Reducer
 */
import { fromJS } from 'immutable';
import {
  SEARCH_CUSTOMERS_REQUESTED,
  SEARCH_CUSTOMERS_SUCCESS,
  SEARCH_CUSTOMERS_FAILURE,
  EXTRACT_TAGS_REQUEST,
  EXTRACT_TAGS_SUCCESS,
  EXTRACT_TAGS_FAILURE,
  UPDATE_PREVIEW_REQUEST,
  UPDATE_PREVIEW_SUCCESS,
  UPDATE_PREVIEW_FAILURE,
  SEND_TEST_MESSAGE_REQUESTED,
  SEND_TEST_MESSAGE_SUCCESS,
  SEND_TEST_MESSAGE_FAILURE,
  CLEAR_CUSTOMER_SEARCH_STATE,
  CLEAR_SEARCH_RESULTS,
  FETCH_TEST_CUSTOMERS_REQUESTED,
  FETCH_TEST_CUSTOMERS_SUCCESS,
  FETCH_TEST_CUSTOMERS_FAILURE,
  FETCH_TEST_GROUPS_REQUESTED,
  FETCH_TEST_GROUPS_SUCCESS,
  FETCH_TEST_GROUPS_FAILURE,
  CREATE_MESSAGE_META_REQUESTED,
  CREATE_MESSAGE_META_SUCCESS,
  CREATE_MESSAGE_META_FAILURE,
  GET_PREFILLED_VALUES_REQUESTED,
  GET_PREFILLED_VALUES_SUCCESS,
  GET_PREFILLED_VALUES_FAILURE,
  CLEAR_PREFILLED_VALUES,
} from './constants';

const initialState = fromJS({
  // Search state
  searchQuery: '',
  customers: [],
  isSearchingCustomer: false,
  searchError: null,
  hasSearched: false,

  // Selected customer and tags
  extractedTags: [],
  requiredTags: [],
  optionalTags: [],
  isExtractingTags: false,
  extractTagsError: null,
  apiWarnings: [],
  apiErrors: [],

  // Preview state
  previewData: null,
  isUpdatingPreview: false,
  updatePreviewError: null,

  // Test email state
  isSendingTestMessage: false,
  sendTestMessageError: null,
  testMessageResponse: null,

  tags: {
    loading: false,
    error: null,
    required: [],
    optional: [],
  },

  // Test Customers
  testCustomers: [],
  isFetchingTestCustomers: false,
  fetchTestCustomersError: null,

  // Test Groups
  testGroups: [],
  isFetchingTestGroups: false,
  fetchTestGroupsError: null,

  messageMetaConfigId: null,
  isCreatingMessageMeta: false,
  createMessageMetaError: null,
  prefilledValues: {},
  isFetchingPrefilledValues: false,
  fetchPrefilledValuesError: null,
});

const previewAndTestReducer = (state = initialState, action) => {
  switch (action.type) {
    // Search Customers
    case SEARCH_CUSTOMERS_REQUESTED:
      return state.set('searchQuery', action.payload.query)
        .set('isSearchingCustomer', true)
        .set('searchError', null)
        .set('hasSearched', false);

    case SEARCH_CUSTOMERS_SUCCESS:
      return state.set('customers', action.payload.customers)
        .set('isSearchingCustomer', false)
        .set('searchError', null)
        .set('hasSearched', true);

    case SEARCH_CUSTOMERS_FAILURE:
      return state.set('customers', [])
        .set('isSearchingCustomer', false)
        .set('searchError', action.payload.error)
        .set('hasSearched', true);

    // Extract Tags
    case EXTRACT_TAGS_REQUEST:
      return state.set('isExtractingTags', true)
        .set('extractTagsError', null)
        .set('apiWarnings', [])
        .set('apiErrors', [])
        .set('tags.loading', true)
        .set('tags.error', null);

    case EXTRACT_TAGS_SUCCESS:
      return state.set('extractedTags', action.payload.extractedtags)
        .set('isExtractingTags', false)
        .set('extractTagsError', null)
        .set('tags.loading', false)
        .set('tags.error', null);

    case EXTRACT_TAGS_FAILURE:
      return state.set('extractedTags', [])
        .set('isExtractingTags', false)
        .set('extractTagsError', action.payload.error)
        .set('apiWarnings', [])
        .set('apiErrors', [])
        .set('tags.loading', false)
        .set('tags.error', action.payload.error);

    // Update Preview
    case UPDATE_PREVIEW_REQUEST:
      return state
        .set('isUpdatingPreview', true)
        .set('updatePreviewError', null)
        // Preserve custom values during update
        .set('lastCustomValues', state.get('customValues'));

    case UPDATE_PREVIEW_SUCCESS:
      return state
        .set('previewData', action.payload.previewData)
        .set('isUpdatingPreview', false)
        .set('updatePreviewError', null)
        // Restore custom values after successful update
        .set('customValues', state.get('lastCustomValues') || state.get('customValues'));

    case UPDATE_PREVIEW_FAILURE:
      return state
        .set('previewData', null)
        .set('isUpdatingPreview', false)
        .set('updatePreviewError', action.payload.error)
        // Restore custom values after failure
        .set('customValues', fromJS(action.payload.customValues));

    // Send Test Email
    case SEND_TEST_MESSAGE_REQUESTED:
      return state.set('isSendingTestMessage', true)
        .set('sendTestMessageError', null)
        .set('testMessageResponse', null);

    case SEND_TEST_MESSAGE_SUCCESS:
      return state.set('testMessageResponse', action.payload.response)
        .set('isSendingTestMessage', false)
        .set('sendTestMessageError', null);

    case SEND_TEST_MESSAGE_FAILURE:
      return state.set('testMessageResponse', action.payload.response)
        .set('isSendingTestMessage', false)
        .set('sendTestMessageError', action.payload.error);

    // Clear Actions
    case CLEAR_SEARCH_RESULTS:
      return state.set('customers', [])
        .set('searchQuery', '')
        .set('hasSearched', false)
        .set('searchError', null);

    case CLEAR_CUSTOMER_SEARCH_STATE:
      return fromJS(initialState);

    // Test Customers
    case FETCH_TEST_CUSTOMERS_REQUESTED:
      return state.set('isFetchingTestCustomers', true)
        .set('fetchTestCustomersError', null);

    case FETCH_TEST_CUSTOMERS_SUCCESS:
      return state.set('isFetchingTestCustomers', false)
        .set('testCustomers', action.payload.customers);

    case FETCH_TEST_CUSTOMERS_FAILURE:
      return state.set('isFetchingTestCustomers', false)
        .set('fetchTestCustomersError', action.payload.error);

    // Test Groups
    case FETCH_TEST_GROUPS_REQUESTED:
      return state.set('isFetchingTestGroups', true)
        .set('fetchTestGroupsError', null);

    case FETCH_TEST_GROUPS_SUCCESS:
      return state.set('isFetchingTestGroups', false)
        .set('testGroups', action.payload.groups);

    case FETCH_TEST_GROUPS_FAILURE:
      return state.set('isFetchingTestGroups', false)
        .set('fetchTestGroupsError', action.payload.error);

    // Create Message Meta
    case CREATE_MESSAGE_META_REQUESTED:
      return state.set('isCreatingMessageMeta', true)
        .set('createMessageMetaError', null);

    case CREATE_MESSAGE_META_SUCCESS:
      return state.set('isCreatingMessageMeta', false)
        .set('messageMetaConfigId', action.payload.response.entity);

    case CREATE_MESSAGE_META_FAILURE:
      return state.set('isCreatingMessageMeta', false)
        .set('createMessageMetaError', action.payload.error);

    // Get Prefilled Values
    case GET_PREFILLED_VALUES_REQUESTED:
      return state.set('isFetchingPrefilledValues', true)
        .set('fetchPrefilledValuesError', null);
    case GET_PREFILLED_VALUES_SUCCESS:
      return state.set('isFetchingPrefilledValues', false)
        .set('prefilledValues', fromJS(action.payload.values));

    case GET_PREFILLED_VALUES_FAILURE:
      return state.set('isFetchingPrefilledValues', false)
        .set('fetchPrefilledValuesError', action.payload.error);

    case CLEAR_PREFILLED_VALUES:
      return state.set('prefilledValues', fromJS({}));

    default:
      return state;
  }
};

export default previewAndTestReducer;
