/**
 * Einwilligungen Reducer
 *
 * Action-Handling und State-Uebergaenge fuer das Einwilligungen-Modul.
 */

import {
  EinwilligungenState,
  EinwilligungenAction,
} from './types'

// =============================================================================
// INITIAL STATE
// =============================================================================

export const initialState: EinwilligungenState = {
  // Data
  catalog: null,
  selectedDataPoints: [],
  privacyPolicy: null,
  cookieBannerConfig: null,
  companyInfo: null,
  consentStatistics: null,

  // UI State
  activeTab: 'catalog',
  isLoading: false,
  isSaving: false,
  error: null,

  // Editor State
  editingDataPoint: null,
  editingSection: null,

  // Preview
  previewLanguage: 'de',
  previewFormat: 'HTML',
}

// =============================================================================
// REDUCER
// =============================================================================

export function einwilligungenReducer(
  state: EinwilligungenState,
  action: EinwilligungenAction
): EinwilligungenState {
  switch (action.type) {
    case 'SET_CATALOG':
      return {
        ...state,
        catalog: action.payload,
        selectedDataPoints: [
          ...action.payload.dataPoints.filter((dp) => dp.isActive !== false).map((dp) => dp.id),
          ...action.payload.customDataPoints.filter((dp) => dp.isActive !== false).map((dp) => dp.id),
        ],
      }

    case 'SET_SELECTED_DATA_POINTS':
      return {
        ...state,
        selectedDataPoints: action.payload,
      }

    case 'TOGGLE_DATA_POINT': {
      const id = action.payload
      const isSelected = state.selectedDataPoints.includes(id)
      return {
        ...state,
        selectedDataPoints: isSelected
          ? state.selectedDataPoints.filter((dpId) => dpId !== id)
          : [...state.selectedDataPoints, id],
      }
    }

    case 'ADD_CUSTOM_DATA_POINT':
      if (!state.catalog) return state
      return {
        ...state,
        catalog: {
          ...state.catalog,
          customDataPoints: [...state.catalog.customDataPoints, action.payload],
          updatedAt: new Date(),
        },
        selectedDataPoints: [...state.selectedDataPoints, action.payload.id],
      }

    case 'UPDATE_DATA_POINT': {
      if (!state.catalog) return state
      const { id, data } = action.payload

      const isCustom = state.catalog.customDataPoints.some((dp) => dp.id === id)

      if (isCustom) {
        return {
          ...state,
          catalog: {
            ...state.catalog,
            customDataPoints: state.catalog.customDataPoints.map((dp) =>
              dp.id === id ? { ...dp, ...data } : dp
            ),
            updatedAt: new Date(),
          },
        }
      } else {
        return {
          ...state,
          catalog: {
            ...state.catalog,
            dataPoints: state.catalog.dataPoints.map((dp) =>
              dp.id === id ? { ...dp, ...data } : dp
            ),
            updatedAt: new Date(),
          },
        }
      }
    }

    case 'DELETE_CUSTOM_DATA_POINT':
      if (!state.catalog) return state
      return {
        ...state,
        catalog: {
          ...state.catalog,
          customDataPoints: state.catalog.customDataPoints.filter((dp) => dp.id !== action.payload),
          updatedAt: new Date(),
        },
        selectedDataPoints: state.selectedDataPoints.filter((id) => id !== action.payload),
      }

    case 'SET_PRIVACY_POLICY':
      return {
        ...state,
        privacyPolicy: action.payload,
      }

    case 'SET_COOKIE_BANNER_CONFIG':
      return {
        ...state,
        cookieBannerConfig: action.payload,
      }

    case 'UPDATE_COOKIE_BANNER_STYLING':
      if (!state.cookieBannerConfig) return state
      return {
        ...state,
        cookieBannerConfig: {
          ...state.cookieBannerConfig,
          styling: {
            ...state.cookieBannerConfig.styling,
            ...action.payload,
          },
          updatedAt: new Date(),
        },
      }

    case 'UPDATE_COOKIE_BANNER_TEXTS':
      if (!state.cookieBannerConfig) return state
      return {
        ...state,
        cookieBannerConfig: {
          ...state.cookieBannerConfig,
          texts: {
            ...state.cookieBannerConfig.texts,
            ...action.payload,
          },
          updatedAt: new Date(),
        },
      }

    case 'SET_COMPANY_INFO':
      return {
        ...state,
        companyInfo: action.payload,
      }

    case 'SET_CONSENT_STATISTICS':
      return {
        ...state,
        consentStatistics: action.payload,
      }

    case 'SET_ACTIVE_TAB':
      return {
        ...state,
        activeTab: action.payload,
      }

    case 'SET_LOADING':
      return {
        ...state,
        isLoading: action.payload,
      }

    case 'SET_SAVING':
      return {
        ...state,
        isSaving: action.payload,
      }

    case 'SET_ERROR':
      return {
        ...state,
        error: action.payload,
      }

    case 'SET_EDITING_DATA_POINT':
      return {
        ...state,
        editingDataPoint: action.payload,
      }

    case 'SET_EDITING_SECTION':
      return {
        ...state,
        editingSection: action.payload,
      }

    case 'SET_PREVIEW_LANGUAGE':
      return {
        ...state,
        previewLanguage: action.payload,
      }

    case 'SET_PREVIEW_FORMAT':
      return {
        ...state,
        previewFormat: action.payload,
      }

    case 'RESET_STATE':
      return initialState

    default:
      return state
  }
}
