<template>
  <ElDialog
    v-model="visible"
    :title="$t('subscription.changeStatus.title')"
    width="520px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ElForm ref="formRef" :model="formModel" :rules="rules" label-width="100px" v-loading="loading">
      <!-- 1. 当前状态 -->
      <ElFormItem :label="$t('subscription.changeStatus.currentStatus')">
        <ElInput :model-value="currentStatusText" disabled />
      </ElFormItem>

      <!-- 2. 状态选择 -->
      <ElFormItem :label="$t('subscription.changeStatus.newStatus')" prop="status">
        <ElSelect v-model="formModel.status" style="width: 100%">
          <ElOption :value="SubscriptionStatus.Active" :label="t('subscription.status.active')" />
          <ElOption
            :value="SubscriptionStatus.Suspended"
            :label="t('subscription.status.suspended')"
          />
          <ElOption
            :value="SubscriptionStatus.Cancelled"
            :label="t('subscription.status.cancelled')"
          />
        </ElSelect>
      </ElFormItem>

      <!-- 3. 备注 -->
      <ElFormItem :label="$t('subscription.changeStatus.reason')" prop="notes">
        <ElInput
          v-model="formModel.notes"
          :placeholder="$t('subscription.changeStatus.reasonPlaceholder')"
          type="textarea"
          :rows="3"
          maxlength="256"
          show-word-limit
        />
      </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 { ref, reactive, computed } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
  import { updateSubscriptionStatus } from '@/api/subscription'
  import { SubscriptionStatus } from '@/enums/SubscriptionStatus'

  defineOptions({ name: 'StatusChangeDialog' })

  const { t } = useI18n()

  const emit = defineEmits<{
    (e: 'success'): void
  }>()

  // 1. 响应式变量
  const visible = ref(false)
  const loading = ref(false)
  const submitting = ref(false)
  const formRef = ref<FormInstance>()
  const currentSubscriptionId = ref<string>('')
  const currentStatus = ref<number | null>(null)

  const formModel = reactive({
    status: SubscriptionStatus.Active as SubscriptionStatus,
    notes: ''
  })

  // 2. 表单校验规则
  const rules = computed<FormRules>(() => ({
    status: [{ required: true, message: t('subscription.changeStatus.validation.statusRequired') }]
  }))

  const currentStatusText = computed(() => {
    if (currentStatus.value === null) return '-'
    return getStatusText(currentStatus.value)
  })

  // 3. 打开弹窗
  const open = (row: Api.Subscription.SubscriptionDto) => {
    visible.value = true

    currentSubscriptionId.value = row.id
    currentStatus.value = row.status
    formModel.status = isSupportedStatus(row.status) ? row.status : SubscriptionStatus.Active
    formModel.notes = ''
    formRef.value?.clearValidate()
  }

  // 4. 关闭处理
  const handleClosed = () => {
    currentSubscriptionId.value = ''
    currentStatus.value = null
    formRef.value?.resetFields()
  }

  // 5. 提交处理
  const handleSubmit = async () => {
    if (!formRef.value || !currentSubscriptionId.value) return

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

      try {
        await ElMessageBox.confirm(
          t('subscription.changeStatus.confirm', {
            status: getStatusText(formModel.status)
          }),
          t('common.tips'),
          {
            confirmButtonText: t('common.confirm'),
            cancelButtonText: t('common.cancel'),
            type: 'warning'
          }
        )

        submitting.value = true

        // 5.1 变更状态
        await updateSubscriptionStatus(currentSubscriptionId.value, {
          status: formModel.status,
          notes: formModel.notes || undefined
        })

        ElMessage.success(t('subscription.changeStatus.success'))
        emit('success')
        visible.value = false
      } catch (error) {
        // 5.2 用户取消操作
        if (error !== 'cancel') {
          console.error('Update subscription status error:', error)
        }
      } finally {
        submitting.value = false
      }
    })
  }

  const isSupportedStatus = (status: number) => {
    return [
      SubscriptionStatus.Active,
      SubscriptionStatus.Suspended,
      SubscriptionStatus.Cancelled
    ].includes(status)
  }

  const getStatusText = (status: number) => {
    switch (status) {
      case SubscriptionStatus.Active:
        return t('subscription.status.active')
      case SubscriptionStatus.Suspended:
        return t('subscription.status.suspended')
      case SubscriptionStatus.Cancelled:
        return t('subscription.status.cancelled')
      default:
        return '-'
    }
  }

  defineExpose({ open })
</script>
