/**
 * Dictionary item state management.
 */

import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { createItem, deleteItem, getItems, updateItem } from '@/api/dictionary/item'
import { HttpError } from '@/utils/http/error'
import { $t } from '@/locales'

export const useDictionaryItemStore = defineStore('dictionaryItemStore', () => {
  const items = ref<Api.Dictionary.DictionaryItemDto[]>([])
  const currentGroupId = ref<string | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)

  const enabledItems = computed(() => items.value.filter((item) => item.isEnabled))
  const defaultItem = computed(() => items.value.find((item) => item.isDefault) ?? null)

  const reset = () => {
    items.value = []
    currentGroupId.value = null
    loading.value = false
    error.value = null
  }

  const fetchItems = async (groupId: string) => {
    error.value = null
    currentGroupId.value = groupId
    const requestGroupId = groupId

    if (requestGroupId.startsWith('temp-')) {
      items.value = []
      loading.value = false
      return null
    }

    loading.value = true
    try {
      const result = await getItems(groupId)
      if (currentGroupId.value !== requestGroupId) {
        return null
      }
      items.value = Array.isArray(result) ? result : []
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.loadItems')
      ElMessage.error(error.value)
      if (currentGroupId.value === requestGroupId) {
        items.value = []
      }
      return null
    } finally {
      if (currentGroupId.value === requestGroupId) {
        loading.value = false
      }
    }
  }

  const createItemAction = async (
    groupId: string,
    data: Api.Dictionary.CreateDictionaryItemRequest
  ) => {
    loading.value = true
    error.value = null

    const snapshot = [...items.value]
    const tempId = `temp-${Date.now()}`
    const tempItem: Api.Dictionary.DictionaryItemDto = {
      id: tempId,
      groupId,
      key: data.key,
      value: data.value,
      isDefault: data.isDefault ?? false,
      isEnabled: data.isEnabled ?? true,
      sortOrder: data.sortOrder ?? 0,
      description: data.description ?? null,
      source: 'tenant',
      rowVersion: ''
    }

    items.value = [tempItem, ...items.value]

    try {
      const result = await createItem(groupId, data)
      const index = items.value.findIndex((item) => item.id === tempId)
      if (index >= 0) {
        items.value.splice(index, 1, result)
      } else {
        items.value = [result, ...items.value]
      }
      return result
    } catch (err) {
      items.value = snapshot
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.createItem')
      ElMessage.error(error.value)
      return null
    } finally {
      loading.value = false
    }
  }

  const updateItemAction = async (
    groupId: string,
    itemId: string,
    data: Api.Dictionary.UpdateDictionaryItemRequest
  ) => {
    loading.value = true
    error.value = null

    const snapshot = [...items.value]
    const index = items.value.findIndex((item) => item.id === itemId)
    if (index >= 0) {
      items.value.splice(index, 1, { ...items.value[index], ...data })
    }

    try {
      const result = await updateItem(groupId, itemId, data)
      if (index >= 0) {
        items.value.splice(index, 1, result)
      }
      return result
    } catch (err) {
      items.value = snapshot
      if (err instanceof HttpError && err.code === 409) {
        ElMessage.warning($t('dictionary.errors.dataConflict'))
      } else {
        error.value = err instanceof Error ? err.message : $t('dictionary.errors.updateItem')
        ElMessage.error(error.value)
      }
      return null
    } finally {
      loading.value = false
    }
  }

  const deleteItemAction = async (groupId: string, itemId: string) => {
    loading.value = true
    error.value = null

    const snapshot = [...items.value]
    items.value = items.value.filter((item) => item.id !== itemId)

    try {
      await deleteItem(groupId, itemId)
      return true
    } catch (err) {
      items.value = snapshot
      error.value = err instanceof Error ? err.message : $t('dictionary.errors.deleteItem')
      ElMessage.error(error.value)
      return false
    } finally {
      loading.value = false
    }
  }

  return {
    items,
    currentGroupId,
    loading,
    error,
    enabledItems,
    defaultItem,
    fetchItems,
    reset,
    createItem: createItemAction,
    updateItem: updateItemAction,
    deleteItem: deleteItemAction
  }
})
