/**
 * Dictionary override state management.
 */

import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  disableOverride,
  enableOverride,
  getOverride,
  getOverrides,
  updateHiddenItems,
  updateSortOrder
} from '@/api/dictionary/override'
import { $t } from '@/locales'

export const useDictionaryOverrideStore = defineStore('dictionaryOverrideStore', () => {
  const overrides = ref<Record<string, Api.Dictionary.OverrideConfigDto>>({})
  const loading = ref(false)
  const error = ref<string | null>(null)

  const normalizeCode = (code: string) => code.trim().toLowerCase()

  const applyOverride = (config: Api.Dictionary.OverrideConfigDto) => {
    overrides.value[normalizeCode(config.systemDictionaryGroupCode)] = config
  }

  const fetchOverrides = async () => {
    loading.value = true
    error.value = null

    try {
      const result = await getOverrides()
      const nextMap: Record<string, Api.Dictionary.OverrideConfigDto> = {}
      result.forEach((item) => {
        nextMap[normalizeCode(item.systemDictionaryGroupCode)] = item
      })
      overrides.value = nextMap
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.loadOverrides')
      ElMessage.error(error.value)
      return null
    } finally {
      loading.value = false
    }
  }

  const fetchOverride = async (groupCode: string) => {
    loading.value = true
    error.value = null

    try {
      const result = await getOverride(groupCode)
      applyOverride(result)
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.loadOverride')
      ElMessage.error(error.value)
      return null
    } finally {
      loading.value = false
    }
  }

  const enableOverrideAction = async (groupCode: string) => {
    loading.value = true
    error.value = null

    try {
      const result = await enableOverride(groupCode)
      applyOverride(result)
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.enableOverride')
      ElMessage.error(error.value)
      return null
    } finally {
      loading.value = false
    }
  }

  const disableOverrideAction = async (groupCode: string) => {
    loading.value = true
    error.value = null

    try {
      await disableOverride(groupCode)
      const key = normalizeCode(groupCode)
      if (overrides.value[key]) {
        overrides.value[key] = { ...overrides.value[key], overrideEnabled: false }
      } else {
        await fetchOverride(groupCode)
      }
      return true
    } catch (err) {
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.disableOverride')
      ElMessage.error(error.value)
      return false
    } finally {
      loading.value = false
    }
  }

  const updateHiddenItemsAction = async (groupCode: string, hiddenIds: string[]) => {
    loading.value = true
    error.value = null

    try {
      const result = await updateHiddenItems(groupCode, hiddenIds)
      applyOverride(result)
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.updateHidden')
      ElMessage.error(error.value)
      return null
    } finally {
      loading.value = false
    }
  }

  const updateCustomSortOrderAction = async (
    groupCode: string,
    sortOrder: Record<string, number>
  ) => {
    loading.value = true
    error.value = null

    try {
      const result = await updateSortOrder(groupCode, sortOrder)
      applyOverride(result)
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.updateSort')
      ElMessage.error(error.value)
      return null
    } finally {
      loading.value = false
    }
  }

  const clearCache = async () => {
    overrides.value = {}
    return fetchOverrides()
  }

  return {
    overrides,
    loading,
    error,
    fetchOverrides,
    fetchOverride,
    enableOverride: enableOverrideAction,
    disableOverride: disableOverrideAction,
    updateHiddenItems: updateHiddenItemsAction,
    updateCustomSortOrder: updateCustomSortOrderAction,
    clearCache
  }
})
