<template>
  <div class="art-page-view">
    <ElCard class="merchant-detail-header" shadow="never" v-loading="loading">
      <div class="header-content">
        <div>
          <div class="header-title">{{ merchant?.name || '-' }}</div>
          <div class="header-meta">
            <span>{{ t('merchant.fields.tenant') }}: {{ merchant?.tenantName || '-' }}</span>
            <span class="ml-4">
              {{ t('merchant.fields.operatingMode') }}: {{ operatingModeText }}
            </span>
          </div>
          <div class="header-tags">
            <ElTag :type="statusType">{{ statusText }}</ElTag>
            <ElTag :type="merchant?.isFrozen ? 'danger' : 'success'">
              {{ merchant?.isFrozen ? t('merchant.frozen.yes') : t('merchant.frozen.no') }}
            </ElTag>
          </div>
        </div>
        <div class="header-actions">
          <ElButton type="primary" :disabled="!merchant" @click="openEdit">
            {{ t('merchant.action.edit') }}
          </ElButton>
          <ElButton :disabled="!merchant" @click="handleExport">
            {{ t('merchant.action.export') }}
          </ElButton>
        </div>
      </div>
    </ElCard>

    <ElCard shadow="never" class="mt-4">
      <ElTabs v-model="activeTab">
        <ElTabPane name="basic" :label="t('merchant.detail.basicInfo')">
          <BasicInfo :merchant="merchant" />
        </ElTabPane>
        <ElTabPane name="subject" :label="t('merchant.detail.subjectInfo')">
          <SubjectInfo :merchant="merchant" />
        </ElTabPane>
        <ElTabPane name="stores" :label="t('merchant.detail.stores')">
          <StoresTab :stores="merchant?.stores || []" />
        </ElTabPane>
        <ElTabPane name="audit" :label="t('merchant.detail.auditHistory')">
          <AuditHistoryTab :merchant-id="merchantId" :refresh-key="refreshKey" />
        </ElTabPane>
        <ElTabPane name="change" :label="t('merchant.detail.changeHistory')">
          <ChangeHistoryTab :merchant-id="merchantId" :refresh-key="refreshKey" />
        </ElTabPane>
      </ElTabs>
    </ElCard>

    <EditDialog ref="editDialogRef" @success="handleUpdated" />
  </div>
</template>

<script setup lang="ts">
  import { computed, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElButton, ElCard, ElMessage, ElTabPane, ElTabs, ElTag } from 'element-plus'
  import { fetchExportMerchantPdf, fetchMerchantDetail } from '@/api/merchant'
  import { MerchantStatus } from '@/enums/MerchantStatus'
  import { OperatingMode } from '@/enums/OperatingMode'
  import BasicInfo from './components/BasicInfo.vue'
  import SubjectInfo from './components/SubjectInfo.vue'
  import StoresTab from './components/StoresTab.vue'
  import AuditHistoryTab from './components/AuditHistoryTab.vue'
  import ChangeHistoryTab from './components/ChangeHistoryTab.vue'
  import EditDialog from './modules/EditDialog.vue'

  defineOptions({ name: 'MerchantDetail' })

  const props = defineProps<{
    merchantId?: string | number
  }>()

  const { t } = useI18n()
  const loading = ref(false)
  const merchant = ref<Api.Merchant.MerchantDetail | null>(null)
  const refreshKey = ref(0)
  const activeTab = ref('basic')
  const editDialogRef = ref<InstanceType<typeof EditDialog>>()

  const merchantId = computed(() => {
    if (props.merchantId === undefined || props.merchantId === null) {
      return undefined
    }
    return String(props.merchantId)
  })

  const statusType = computed(() => {
    switch (merchant.value?.status) {
      case MerchantStatus.Pending:
        return 'warning'
      case MerchantStatus.Approved:
        return 'success'
      case MerchantStatus.Rejected:
        return 'danger'
      case MerchantStatus.Frozen:
        return 'info'
      default:
        return 'info'
    }
  })

  const statusText = computed(() => {
    switch (merchant.value?.status) {
      case MerchantStatus.Pending:
        return t('merchant.status.pending')
      case MerchantStatus.Approved:
        return t('merchant.status.approved')
      case MerchantStatus.Rejected:
        return t('merchant.status.rejected')
      case MerchantStatus.Frozen:
        return t('merchant.status.frozen')
      default:
        return t('merchant.status.unknown')
    }
  })

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

  const loadDetail = async () => {
    if (!merchantId.value) {
      merchant.value = null
      return
    }

    loading.value = true
    try {
      const result = await fetchMerchantDetail(merchantId.value)
      merchant.value = result || null
    } finally {
      loading.value = false
    }
  }

  const openEdit = () => {
    if (merchant.value) {
      editDialogRef.value?.open(merchant.value)
    }
  }

  const handleUpdated = (updated: Api.Merchant.MerchantDetail, requiresReview: boolean) => {
    merchant.value = updated
    refreshKey.value += 1
    if (requiresReview) {
      ElMessage.warning(t('merchant.message.updateRequiresReview'))
    }
  }

  const handleExport = async () => {
    if (!merchantId.value) return
    try {
      const blob = await fetchExportMerchantPdf(merchantId.value)
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `merchant_${merchantId.value}.pdf`
      link.click()
      window.URL.revokeObjectURL(url)
    } catch {
      // errors are handled globally
    }
  }

  watch(
    merchantId,
    () => {
      loadDetail()
    },
    { immediate: true }
  )
</script>

<style scoped>
  .merchant-detail-header .header-content {
    display: flex;
    gap: 16px;
    align-items: center;
    justify-content: space-between;
  }

  .merchant-detail-header .header-title {
    font-size: 20px;
    font-weight: 600;
  }

  .merchant-detail-header .header-meta {
    margin-top: 6px;
    font-size: 13px;
    color: var(--el-text-color-secondary);
  }

  .merchant-detail-header .header-tags {
    display: flex;
    gap: 8px;
    margin-top: 8px;
  }

  .merchant-detail-header .header-actions {
    display: flex;
    flex-shrink: 0;
    gap: 8px;
  }
</style>
