<template>
  <ElDialog
    v-model="visible"
    :title="t('merchant.review.title')"
    width="900px"
    top="6vh"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ElSkeleton :loading="detailLoading" animated>
      <template #template>
        <div class="space-y-3">
          <div class="h-6 w-2/5 rounded bg-[var(--el-fill-color-light)]"></div>
          <div class="h-24 w-full rounded bg-[var(--el-fill-color-light)]"></div>
        </div>
      </template>
      <template #default>
        <ElDescriptions :column="2" border>
          <ElDescriptionsItem :label="t('merchant.fields.name')">
            {{ merchantDetail?.name || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem :label="t('merchant.list.table.tenantName')">
            {{ merchantDetail?.tenantName || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem :label="t('merchant.fields.operatingMode')">
            {{ getOperatingModeText(merchantDetail?.operatingMode) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem :label="t('merchant.fields.licenseNumber')">
            {{ merchantDetail?.licenseNumber || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem :label="t('merchant.fields.legalRepresentative')">
            {{ merchantDetail?.legalRepresentative || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem :label="t('merchant.fields.registeredAddress')">
            {{ merchantDetail?.registeredAddress || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem :label="t('merchant.fields.contactPhone')">
            {{ merchantDetail?.contactPhone || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem :label="t('merchant.fields.contactEmail')">
            {{ merchantDetail?.contactEmail || '-' }}
          </ElDescriptionsItem>
        </ElDescriptions>

        <ElDivider content-position="left" class="my-3">{{
          t('merchant.review.section.action')
        }}</ElDivider>
        <ElForm ref="formRef" :model="form" :rules="rules" label-width="90px">
          <ElFormItem :label="t('merchant.review.claim')">
            <div class="w-full space-y-2">
              <div class="flex items-center justify-between gap-2">
                <div class="flex items-center gap-2 text-sm">
                  <template v-if="reviewClaim">
                    <ElTag type="warning">{{ t('merchant.review.claimed') }}</ElTag>
                    <span>{{ reviewClaim.claimedByName || '-' }}</span>
                  </template>
                  <template v-else>
                    <ElTag type="success">{{ t('merchant.review.unclaimed') }}</ElTag>
                  </template>
                </div>
                <div class="flex items-center gap-2">
                  <ElButton
                    v-if="!reviewClaim"
                    size="small"
                    type="primary"
                    :loading="claimLoading"
                    @click="handleClaim"
                  >
                    {{ t('merchant.review.claim') }}
                  </ElButton>
                  <ElButton
                    v-else-if="isClaimedByMe"
                    size="small"
                    :loading="claimLoading"
                    @click="handleReleaseClaim"
                  >
                    {{ t('merchant.review.release') }}
                  </ElButton>
                </div>
              </div>
              <ElAlert
                v-if="reviewClaim && !isClaimedByMe"
                type="warning"
                :closable="false"
                :title="t('merchant.review.readonlyTip')"
              />
            </div>
          </ElFormItem>
          <ElFormItem :label="t('merchant.review.result')" prop="approve">
            <ElRadioGroup v-model="form.approve" :disabled="!canOperate">
              <ElRadio :value="true">{{ t('merchant.review.approve') }}</ElRadio>
              <ElRadio :value="false">{{ t('merchant.review.reject') }}</ElRadio>
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem
            v-if="form.approve === false"
            :label="t('merchant.review.reason')"
            prop="remarks"
          >
            <ElInput
              v-model="form.remarks"
              type="textarea"
              :rows="3"
              :disabled="!canOperate"
              :placeholder="t('merchant.review.reasonPlaceholder')"
            />
          </ElFormItem>
        </ElForm>

        <ElDivider content-position="left" class="my-3">{{
          t('merchant.review.section.history')
        }}</ElDivider>
        <AuditTimeline :items="auditLogs" />
      </template>
    </ElSkeleton>
    <template #footer>
      <ElButton @click="visible = false">{{ t('common.cancel') }}</ElButton>
      <ElButton type="primary" :loading="loading" @click="handleSubmit">
        {{ t('common.confirm') }}
      </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { computed, reactive, ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
  import { useUserStore } from '@/store/modules/user'
  import { OperatingMode } from '@/enums/OperatingMode'
  import {
    fetchClaimMerchantReview,
    fetchMerchantAuditHistory,
    fetchMerchantDetail,
    fetchMerchantReviewClaim,
    fetchReleaseMerchantReview,
    fetchReviewMerchant
  } from '@/api/merchant'
  import AuditTimeline from '@/components/merchant/AuditTimeline.vue'

  const { t } = useI18n()
  const userStore = useUserStore()

  const visible = ref(false)
  const loading = ref(false)
  const detailLoading = ref(false)
  const claimLoading = ref(false)
  const merchantId = ref('')
  const merchantDetail = ref<Api.Merchant.MerchantDetail>()
  const reviewClaim = ref<Api.Merchant.ClaimInfo | null>(null)
  const auditLogs = ref<Api.Merchant.MerchantAuditRecord[]>([])
  const formRef = ref<FormInstance>()

  const form = reactive({
    approve: true,
    remarks: ''
  })

  const rules = computed<FormRules>(() => ({
    approve: [{ required: true, message: t('merchant.review.selectResult'), trigger: 'change' }],
    remarks: [
      {
        validator: (_rule, value: unknown, callback) => {
          if (form.approve !== false) return callback()
          const text = typeof value === 'string' ? value.trim() : ''
          if (!text) return callback(new Error(t('merchant.review.reasonPlaceholder')))
          return callback()
        },
        trigger: 'blur'
      }
    ]
  }))

  const currentUserId = computed(() => String(userStore.getUserInfo?.userId || ''))
  const isClaimedByMe = computed(
    () => !!reviewClaim.value && reviewClaim.value.claimedBy === currentUserId.value
  )
  const canOperate = computed(() => !!reviewClaim.value && isClaimedByMe.value)

  const open = async (row: Api.Merchant.MerchantReviewListItem) => {
    merchantId.value = row.id
    form.approve = true
    form.remarks = ''
    visible.value = true
    await Promise.all([fetchDetail(), fetchClaim(), fetchAuditLogs()])
  }

  const handleClosed = () => {
    merchantId.value = ''
    merchantDetail.value = undefined
    reviewClaim.value = null
    auditLogs.value = []
    formRef.value?.resetFields()
  }

  const fetchDetail = async () => {
    if (!merchantId.value) return
    try {
      detailLoading.value = true
      merchantDetail.value = await fetchMerchantDetail(merchantId.value)
    } finally {
      detailLoading.value = false
    }
  }

  const fetchClaim = async () => {
    if (!merchantId.value) return
    try {
      claimLoading.value = true
      reviewClaim.value = await fetchMerchantReviewClaim(merchantId.value)
    } catch {
      reviewClaim.value = null
    } finally {
      claimLoading.value = false
    }
  }

  const fetchAuditLogs = async () => {
    if (!merchantId.value) return
    try {
      auditLogs.value = await fetchMerchantAuditHistory(merchantId.value)
    } catch {
      auditLogs.value = []
    }
  }

  const handleClaim = async () => {
    if (!merchantId.value) return
    try {
      claimLoading.value = true
      reviewClaim.value = await fetchClaimMerchantReview(merchantId.value)
      await fetchAuditLogs()
    } finally {
      claimLoading.value = false
    }
  }

  const handleReleaseClaim = async () => {
    if (!merchantId.value) return
    try {
      claimLoading.value = true
      reviewClaim.value = await fetchReleaseMerchantReview(merchantId.value)
      await fetchAuditLogs()
    } finally {
      claimLoading.value = false
    }
  }

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

    if (!reviewClaim.value) {
      ElMessage.warning(t('merchant.review.needClaim'))
      return
    }

    if (!isClaimedByMe.value) {
      ElMessage.warning(t('merchant.review.readonlyTip'))
      return
    }

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

      try {
        loading.value = true
        await fetchReviewMerchant(merchantId.value, {
          approve: form.approve,
          remarks: form.approve ? undefined : form.remarks.trim()
        })
        ElMessage.success(t('merchant.review.success'))
        visible.value = false
        emit('success')
      } finally {
        loading.value = false
      }
    })
  }

  const getOperatingModeText = (mode?: number) => {
    switch (mode) {
      case OperatingMode.SameEntity:
        return t('merchant.operatingMode.same')
      case OperatingMode.DifferentEntity:
        return t('merchant.operatingMode.different')
      default:
        return '-'
    }
  }

  const emit = defineEmits(['success'])

  defineExpose({ open })
</script>
