<template>
  <ElDialog
    :model-value="modelValue"
    :title="dialogTitle"
    width="520px"
    destroy-on-close
    @close="handleClose"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="110px">
      <ElFormItem :label="t('dictionary.common.code')" prop="code">
        <ElInput
          v-model="form.code"
          :disabled="isEdit"
          :placeholder="t('dictionary.group.codePlaceholder')"
        />
      </ElFormItem>
      <ElFormItem :label="t('dictionary.common.name')" prop="name">
        <ElInput v-model="form.name" :placeholder="t('dictionary.group.namePlaceholder')" />
      </ElFormItem>
      <ElFormItem :label="t('dictionary.common.scope')" prop="scope">
        <ElSelect
          v-model="form.scope"
          :disabled="isEdit || !allowScopeSelection"
          :placeholder="t('dictionary.group.scopePlaceholder')"
        >
          <ElOption :value="DictionaryScope.System" :label="t('dictionary.common.system')" />
          <ElOption :value="DictionaryScope.Business" :label="t('dictionary.common.business')" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem :label="t('dictionary.group.allowOverride')" prop="allowOverride">
        <ElSwitch v-model="form.allowOverride" />
      </ElFormItem>
      <ElFormItem v-if="isEdit" :label="t('dictionary.common.enabled')" prop="isEnabled">
        <ElSwitch v-model="form.isEnabled" />
      </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 { useDictionaryGroupStore } from '@/store/modules/dictionaryGroup'
  import { DictionaryScope } from '@/enums/Dictionary'

  defineOptions({ name: 'GroupFormDialog' })

  interface Props {
    modelValue: boolean
    mode: 'create' | 'edit'
    group?: Api.Dictionary.DictionaryGroupDto | null
    defaultScope?: DictionaryScope
    allowScopeSelection?: boolean
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    mode: 'create',
    group: null,
    defaultScope: DictionaryScope.Business,
    allowScopeSelection: true
  })

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

  const groupStore = useDictionaryGroupStore()
  const { t } = useI18n()
  const formRef = ref<FormInstance>()
  const submitting = ref(false)

  const form = reactive({
    code: '',
    name: '',
    scope: props.defaultScope,
    allowOverride: false,
    isEnabled: true,
    description: ''
  })

  const isEdit = computed(() => props.mode === 'edit')

  const dialogTitle = computed(() =>
    isEdit.value ? t('dictionary.group.editTitle') : t('dictionary.group.createTitle')
  )

  const rules = computed<FormRules>(() => ({
    code: [
      { required: true, message: t('dictionary.group.codeRequired'), trigger: 'blur' },
      {
        min: ValidationConstraints.codeMinLength,
        max: ValidationConstraints.codeMaxLength,
        message: t('dictionary.group.codeLength', {
          min: ValidationConstraints.codeMinLength,
          max: ValidationConstraints.codeMaxLength
        }),
        trigger: 'blur'
      },
      {
        pattern: /^[a-zA-Z0-9_]+$/,
        message: t('dictionary.group.codePattern'),
        trigger: 'blur'
      }
    ],
    name: [
      { required: true, message: t('dictionary.group.nameRequired'), trigger: 'blur' },
      {
        max: ValidationConstraints.nameMaxLength,
        message: t('dictionary.group.nameTooLong'),
        trigger: 'blur'
      }
    ],
    description: [
      {
        max: ValidationConstraints.descriptionMaxLength,
        message: t('dictionary.group.descriptionTooLong'),
        trigger: 'blur'
      }
    ]
  }))

  const resetForm = () => {
    form.code = ''
    form.name = ''
    form.scope = props.defaultScope
    form.allowOverride = false
    form.isEnabled = true
    form.description = ''
  }

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

      if (props.mode === 'edit' && props.group) {
        form.code = props.group.code
        form.name = props.group.name
        form.scope = props.group.scope
        form.allowOverride = props.group.allowOverride
        form.isEnabled = props.group.isEnabled
        form.description = props.group.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.group) {
          if (!props.group.rowVersion) {
            ElMessage.error(t('dictionary.group.rowVersionMissing'))
            return
          }

          const result = await groupStore.updateGroup(props.group.id, {
            name: form.name,
            description: form.description || null,
            allowOverride: form.allowOverride,
            isEnabled: form.isEnabled,
            rowVersion: props.group.rowVersion
          })

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

        const result = await groupStore.createGroup({
          code: form.code,
          name: form.name,
          scope: form.scope,
          allowOverride: form.allowOverride,
          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>
