<template>
  <ElDialog
    :model-value="modelValue"
    :title="dialogTitle"
    width="560px"
    destroy-on-close
    @close="handleClose"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="110px">
      <ElFormItem :label="t('dictionary.common.key')" prop="key">
        <ElInput
          v-model="form.key"
          :disabled="isEdit"
          :placeholder="t('dictionary.item.keyPlaceholder')"
        />
      </ElFormItem>
      <ElFormItem :label="t('dictionary.common.value')" prop="value">
        <I18nValueEditor v-model="form.value" />
      </ElFormItem>
      <ElFormItem :label="t('dictionary.common.default')" prop="isDefault">
        <ElSwitch v-model="form.isDefault" />
      </ElFormItem>
      <ElFormItem :label="t('dictionary.common.enabled')" prop="isEnabled">
        <ElSwitch v-model="form.isEnabled" />
      </ElFormItem>
      <ElFormItem :label="t('dictionary.common.sortOrder')" prop="sortOrder">
        <ElInputNumber v-model="form.sortOrder" :min="0" :step="10" />
      </ElFormItem>
      <ElFormItem :label="t('dictionary.common.description')" prop="description">
        <ElInput v-model="form.description" type="textarea" :rows="3" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="handleClose">{{ t('dictionary.common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="submitting" @click="handleSubmit">
          {{ t('dictionary.common.confirm') }}
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { computed, reactive, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { ValidationConstraints } from '@/types/dictionary'
  import { useDictionaryItemStore } from '@/store/modules/dictionaryItem'
  import I18nValueEditor from './I18nValueEditor.vue'

  defineOptions({ name: 'ItemFormDialog' })

  interface Props {
    modelValue: boolean
    mode: 'create' | 'edit'
    groupId?: string
    item?: Api.Dictionary.DictionaryItemDto | null
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    mode: 'create',
    groupId: undefined,
    item: null
  })

  const emit = defineEmits<{
    (event: 'update:modelValue', value: boolean): void
    (event: 'success', value: Api.Dictionary.DictionaryItemDto): void
  }>()

  const itemStore = useDictionaryItemStore()
  const { t } = useI18n()
  const formRef = ref<FormInstance>()
  const submitting = ref(false)

  const form = reactive({
    key: '',
    value: {} as Record<string, string>,
    isDefault: false,
    isEnabled: true,
    sortOrder: 0,
    description: ''
  })

  const isEdit = computed(() => props.mode === 'edit')
  const dialogTitle = computed(() =>
    isEdit.value ? t('dictionary.item.editTitle') : t('dictionary.item.createTitle')
  )

  const rules = computed<FormRules>(() => ({
    key: [
      { required: true, message: t('dictionary.item.keyRequired'), trigger: 'blur' },
      {
        max: ValidationConstraints.keyMaxLength,
        message: t('dictionary.item.keyTooLong'),
        trigger: 'blur'
      }
    ],
    value: [
      {
        validator: (_rule, value, callback) => {
          const hasValue = value && (value['zh-CN'] || value.en)
          if (!hasValue) {
            callback(new Error(t('dictionary.item.valueRequired')))
            return
          }
          callback()
        },
        trigger: 'change'
      }
    ],
    description: [
      {
        max: ValidationConstraints.descriptionMaxLength,
        message: t('dictionary.item.descriptionTooLong'),
        trigger: 'blur'
      }
    ]
  }))

  const resetForm = () => {
    form.key = ''
    form.value = {}
    form.isDefault = false
    form.isEnabled = true
    form.sortOrder = 0
    form.description = ''
  }

  watch(
    () => [props.modelValue, props.item, props.mode],
    () => {
      if (!props.modelValue) return

      if (props.mode === 'edit' && props.item) {
        form.key = props.item.key
        form.value = { ...props.item.value }
        form.isDefault = props.item.isDefault
        form.isEnabled = props.item.isEnabled
        form.sortOrder = props.item.sortOrder
        form.description = props.item.description ?? ''
      } else {
        resetForm()
      }
    }
  )

  const handleClose = () => {
    emit('update:modelValue', false)
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (!valid) return

      submitting.value = true
      try {
        if (props.mode === 'edit' && props.item) {
          if (!props.item.rowVersion) {
            ElMessage.error(t('dictionary.item.rowVersionMissing'))
            return
          }

          const result = await itemStore.updateItem(props.item.groupId, props.item.id, {
            key: form.key,
            value: form.value,
            isDefault: form.isDefault,
            isEnabled: form.isEnabled,
            sortOrder: form.sortOrder,
            description: form.description || null,
            rowVersion: props.item.rowVersion
          })

          if (result) {
            emit('success', result)
            handleClose()
          }
          return
        }

        if (!props.groupId) {
          ElMessage.error(t('dictionary.item.groupNotSelected'))
          return
        }

        const result = await itemStore.createItem(props.groupId, {
          key: form.key,
          value: form.value,
          isDefault: form.isDefault,
          isEnabled: form.isEnabled,
          sortOrder: form.sortOrder,
          description: form.description || null
        })

        if (result) {
          emit('success', result)
          handleClose()
        }
      } finally {
        submitting.value = false
      }
    })
  }
</script>

<style scoped>
  .dialog-footer {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }
</style>
