<template>
  <ElDialog
    v-model="visible"
    :title="t('merchant.action.edit')"
    width="560px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ElForm ref="formRef" :model="formModel" :rules="rules" label-width="120px">
      <ElFormItem :label="t('merchant.fields.name')" prop="name">
        <ElInput v-model="formModel.name" :placeholder="t('merchant.placeholder.name')" />
      </ElFormItem>
      <ElFormItem :label="t('merchant.fields.licenseNumber')" prop="licenseNumber">
        <ElInput
          v-model="formModel.licenseNumber"
          :placeholder="t('merchant.placeholder.licenseNumber')"
        />
      </ElFormItem>
      <ElFormItem :label="t('merchant.fields.legalRepresentative')" prop="legalRepresentative">
        <ElInput
          v-model="formModel.legalRepresentative"
          :placeholder="t('merchant.placeholder.legalRepresentative')"
        />
      </ElFormItem>
      <ElFormItem :label="t('merchant.fields.registeredAddress')" prop="registeredAddress">
        <ElInput
          v-model="formModel.registeredAddress"
          :placeholder="t('merchant.placeholder.registeredAddress')"
        />
      </ElFormItem>
      <ElFormItem :label="t('merchant.fields.contactPhone')" prop="contactPhone">
        <ElInput
          v-model="formModel.contactPhone"
          :placeholder="t('merchant.placeholder.contactPhone')"
        />
      </ElFormItem>
      <ElFormItem :label="t('merchant.fields.contactEmail')" prop="contactEmail">
        <ElInput
          v-model="formModel.contactEmail"
          :placeholder="t('merchant.placeholder.contactEmail')"
        />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="visible = false">{{ t('common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="submitting" @click="handleSubmit">
          {{ t('common.confirm') }}
        </ElButton>
      </span>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { reactive, ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
  import { fetchUpdateMerchant } from '@/api/merchant'
  import { isHttpError } from '@/utils/http/error'

  interface Emits {
    (e: 'success', merchant: Api.Merchant.MerchantDetail, requiresReview: boolean): void
  }

  const emit = defineEmits<Emits>()
  const { t } = useI18n()

  const visible = ref(false)
  const submitting = ref(false)
  const formRef = ref<FormInstance>()
  const currentMerchantId = ref<string | null>(null)
  const currentRowVersion = ref<string | null>(null)

  const formModel = reactive({
    name: '',
    licenseNumber: '',
    legalRepresentative: '',
    registeredAddress: '',
    contactPhone: '',
    contactEmail: ''
  })

  const rules: FormRules = {
    name: [{ required: true, message: t('merchant.rules.nameRequired'), trigger: 'blur' }],
    contactPhone: [
      { required: true, message: t('merchant.rules.contactPhoneRequired'), trigger: 'blur' }
    ],
    contactEmail: [
      { type: 'email', message: t('merchant.rules.contactEmailInvalid'), trigger: 'blur' }
    ]
  }

  const open = (merchant: Api.Merchant.MerchantDetail) => {
    currentMerchantId.value = merchant.id
    currentRowVersion.value = merchant.rowVersion || null
    formModel.name = merchant.name || ''
    formModel.licenseNumber = merchant.licenseNumber || ''
    formModel.legalRepresentative = merchant.legalRepresentative || ''
    formModel.registeredAddress = merchant.registeredAddress || ''
    formModel.contactPhone = merchant.contactPhone || ''
    formModel.contactEmail = merchant.contactEmail || ''
    visible.value = true
  }

  const handleClosed = () => {
    formRef.value?.resetFields()
    currentMerchantId.value = null
    currentRowVersion.value = null
  }

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

    const merchantId = currentMerchantId.value
    if (!merchantId) return

    const rowVersion = currentRowVersion.value
    if (!rowVersion) {
      ElMessage.error(t('merchant.message.rowVersionMissing'))
      return
    }

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

      submitting.value = true
      try {
        const result = await fetchUpdateMerchant(
          merchantId,
          {
            name: formModel.name,
            licenseNumber: formModel.licenseNumber,
            legalRepresentative: formModel.legalRepresentative,
            registeredAddress: formModel.registeredAddress,
            contactPhone: formModel.contactPhone,
            contactEmail: formModel.contactEmail,
            rowVersion
          },
          { showErrorMessage: false }
        )

        ElMessage.success(t('merchant.message.updateSuccess'))
        emit('success', result.merchant, result.requiresReview)
        visible.value = false
      } catch (error) {
        if (isHttpError(error) && error.code === 422) {
          const data = error.data as Api.Merchant.UpdateMerchantResult | undefined
          if (data?.merchant) {
            emit('success', data.merchant, true)
            visible.value = false
            return
          }
        }

        if (isHttpError(error)) {
          ElMessage.error(error.message)
        }
      } finally {
        submitting.value = false
      }
    })
  }

  defineExpose({ open })
</script>
