<template>
  <ElDrawer
    v-model="visible"
    :title="$t('subscription.detail.title')"
    size="600px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <div v-loading="loading" class="drawer-content">
      <!-- 1. 基本信息 -->
      <ElCard shadow="never" class="info-card">
        <template #header>
          <div class="card-header">
            <ArtSvgIcon icon="ri:information-line" class="header-icon" />
            <span>{{ $t('subscription.detail.basicInfo') }}</span>
          </div>
        </template>
        <div class="info-item">
          <span class="label">{{ $t('subscription.detail.tenantName') }}:</span>
          <span class="value">{{ detailData?.tenantName || '-' }}</span>
        </div>
        <div class="info-item">
          <span class="label">{{ $t('subscription.detail.currentPackage') }}:</span>
          <span class="value">{{
            detailData?.package?.name || detailData?.tenantPackageName || '-'
          }}</span>
        </div>
        <div class="info-item">
          <span class="label">{{ $t('subscription.detail.status') }}:</span>
          <ElTag :type="getStatusType(detailData?.status)">
            {{ getStatusText(detailData?.status) }}
          </ElTag>
        </div>
        <div class="info-item">
          <span class="label">{{ $t('subscription.detail.effectiveDate') }}:</span>
          <span class="value">{{ formatDate(detailData?.effectiveFrom) }}</span>
        </div>
        <div class="info-item">
          <span class="label">{{ $t('subscription.detail.expireDate') }}:</span>
          <span class="value">{{ formatDate(detailData?.effectiveTo) }}</span>
        </div>
        <div class="info-item">
          <span class="label">{{ $t('subscription.detail.autoRenew') }}:</span>
          <div class="auto-renew-wrap">
            <ElSwitch
              v-model="autoRenewDraft"
              :loading="isSavingAutoRenew"
              :disabled="loading || !detailData"
              @change="handleAutoRenewChange"
            />
            <ElTag :type="autoRenewDraft ? 'success' : 'info'">
              {{ autoRenewDraft ? $t('common.yes') : $t('common.no') }}
            </ElTag>
          </div>
        </div>
      </ElCard>

      <!-- 2. 备注 -->
      <ElCard shadow="never" class="notes-card">
        <template #header>
          <div class="card-header notes-header">
            <div class="notes-title">
              <ArtSvgIcon icon="ri:sticky-note-line" class="header-icon" />
              <span>{{ $t('subscription.detail.notes') }}</span>
            </div>
            <ElButton
              type="primary"
              size="small"
              :loading="savingNotes"
              :disabled="!isNotesChanged"
              @click="handleSaveNotes"
            >
              {{ $t('subscription.detail.saveNotes') }}
            </ElButton>
          </div>
        </template>

        <ElInput
          v-model="notesDraft"
          type="textarea"
          :rows="4"
          maxlength="512"
          show-word-limit
          :placeholder="$t('subscription.detail.notesPlaceholder')"
        />
      </ElCard>

      <!-- 3. 配额使用情况 -->
      <ElCard shadow="never" class="quota-card">
        <template #header>
          <div class="card-header">
            <ArtSvgIcon icon="ri:stack-line" class="header-icon" />
            <span>{{ $t('subscription.detail.quotaUsage') }}</span>
          </div>
        </template>
        <div v-if="detailData?.quotaUsages && detailData.quotaUsages.length > 0" class="quota-list">
          <div v-for="quota in detailData.quotaUsages" :key="quota.quotaType" class="quota-item">
            <div class="quota-label">{{ getQuotaName(quota.quotaType) }}</div>
            <ElProgress
              :percentage="
                getQuotaUsagePercentage(quota) ??
                calculatePercentage(getQuotaUsedValue(quota), getQuotaLimitValue(quota))
              "
              :status="getProgressStatus(getQuotaUsedValue(quota), getQuotaLimitValue(quota))"
            />
            <div class="quota-text">
              {{ getQuotaUsedValue(quota) }} / {{ formatQuota(getQuotaLimitValue(quota)) }}
              {{ getQuotaUnit(quota.quotaType) }}
            </div>
          </div>
        </div>
        <ElEmpty v-else :description="$t('subscription.detail.noQuota')" />
      </ElCard>

      <!-- 4. 变更历史 -->
      <ElCard shadow="never" class="history-card">
        <template #header>
          <div class="card-header">
            <ArtSvgIcon icon="ri:history-line" class="header-icon" />
            <span>{{ $t('subscription.detail.changeHistory') }}</span>
          </div>
        </template>
        <ElTimeline v-if="detailData?.changeHistory && detailData.changeHistory.length > 0">
          <ElTimelineItem
            v-for="(item, index) in detailData.changeHistory"
            :key="index"
            :timestamp="formatDateTime(item.createdAt)"
            placement="top"
          >
            <div class="history-item">
              <div class="history-title">{{ getHistoryTitle(item) }}</div>
              <div class="history-description">{{ item.notes || '-' }}</div>
            </div>
          </ElTimelineItem>
        </ElTimeline>
        <ElEmpty v-else :description="$t('subscription.detail.noHistory')" />
      </ElCard>
    </div>
  </ElDrawer>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { getSubscriptionDetail, updateSubscription } from '@/api/subscription'
  import { SubscriptionStatus } from '@/enums/SubscriptionStatus'
  import ArtSvgIcon from '@/components/core/base/art-svg-icon/index.vue'
  import {
    ElButton,
    ElCard,
    ElDrawer,
    ElEmpty,
    ElInput,
    ElMessage,
    ElProgress,
    ElSwitch,
    ElTag,
    ElTimeline,
    ElTimelineItem
  } from 'element-plus'

  defineOptions({ name: 'SubscriptionDetailDrawer' })

  const { t } = useI18n()

  // 1. 响应式变量
  const visible = ref(false)
  const loading = ref(false)
  const detailData = ref<Api.Subscription.SubscriptionDetailDto | null>(null)
  const currentSubscriptionId = ref<string>('')
  const notesDraft = ref<string>('')
  const savingNotes = ref(false)
  const autoRenewDraft = ref(false)
  const isSavingAutoRenew = ref(false)

  const isNotesChanged = computed(() => {
    if (!detailData.value) return false
    return (detailData.value.notes || '') !== notesDraft.value
  })

  // 2. 打开抽屉
  const open = async (row: Api.Subscription.SubscriptionDto) => {
    visible.value = true
    loading.value = true
    currentSubscriptionId.value = row.id

    try {
      detailData.value = await getSubscriptionDetail(row.id)
      notesDraft.value = detailData.value?.notes || ''
      autoRenewDraft.value = detailData.value?.autoRenew ?? false
    } catch (error) {
      console.error('Failed to load subscription detail:', error)
    } finally {
      loading.value = false
    }
  }

  // 3. 关闭处理
  const handleClosed = () => {
    currentSubscriptionId.value = ''
    detailData.value = null
    notesDraft.value = ''
    autoRenewDraft.value = false
  }

  // 4. 保存备注
  const handleSaveNotes = async () => {
    if (!currentSubscriptionId.value) return

    savingNotes.value = true
    try {
      // 4.1 保存备注
      const result = await updateSubscription(currentSubscriptionId.value, {
        notes: notesDraft.value || undefined
      })

      // 4.2 刷新抽屉数据
      detailData.value = {
        ...(detailData.value as Api.Subscription.SubscriptionDetailDto),
        ...result,
        notes: notesDraft.value || undefined
      }

      ElMessage.success(t('subscription.detail.saveNotesSuccess'))
    } catch (error) {
      console.error('Save subscription notes error:', error)
    } finally {
      savingNotes.value = false
    }
  }

  // 5. 切换自动续费
  const handleAutoRenewChange = async (value: string | number | boolean) => {
    if (!currentSubscriptionId.value) return

    const nextValue = typeof value === 'boolean' ? value : Boolean(value)

    isSavingAutoRenew.value = true
    try {
      // 5.1 更新自动续费开关
      const result = await updateSubscription(currentSubscriptionId.value, {
        autoRenew: nextValue
      })

      // 5.2 刷新抽屉数据
      detailData.value = {
        ...(detailData.value as Api.Subscription.SubscriptionDetailDto),
        ...result,
        autoRenew: nextValue
      }

      ElMessage.success(t('subscription.detail.autoRenewUpdateSuccess'))
    } catch (error) {
      // 5.3 回滚开关显示
      autoRenewDraft.value = !nextValue
      console.error('Update subscription auto renew error:', error)
      ElMessage.error(t('subscription.detail.autoRenewUpdateFailed'))
    } finally {
      isSavingAutoRenew.value = false
    }
  }

  // 6. 状态处理
  const getStatusType = (status?: number) => {
    if (status === undefined) return 'info'
    switch (status) {
      case SubscriptionStatus.Pending:
        return 'warning'
      case SubscriptionStatus.Active:
        return 'success'
      case SubscriptionStatus.GracePeriod:
        return 'warning'
      case SubscriptionStatus.Cancelled:
        return 'info'
      case SubscriptionStatus.Suspended:
        return 'danger'
      default:
        return 'info'
    }
  }

  const getStatusText = (status?: number) => {
    if (status === undefined) return '-'
    switch (status) {
      case SubscriptionStatus.Pending:
        return t('subscription.status.pending')
      case SubscriptionStatus.Active:
        return t('subscription.status.active')
      case SubscriptionStatus.GracePeriod:
        return t('subscription.status.gracePeriod')
      case SubscriptionStatus.Cancelled:
        return t('subscription.status.cancelled')
      case SubscriptionStatus.Suspended:
        return t('subscription.status.suspended')
      default:
        return '-'
    }
  }

  // 6. 配额处理
  type QuotaItem = Api.Subscription.SubscriptionDetailDto['quotaUsages'][number] &
    Record<string, any>

  const getQuotaUsedValue = (quota: QuotaItem) => {
    const raw = quota.usedValue ?? quota.used ?? 0
    const value = Number(raw)
    return Number.isFinite(value) ? value : 0
  }

  const getQuotaLimitValue = (quota: QuotaItem) => {
    const raw = quota.limitValue ?? quota.limit ?? null
    if (raw === null || raw === undefined) return null
    const value = Number(raw)
    return Number.isFinite(value) ? value : null
  }

  const getQuotaUsagePercentage = (quota: QuotaItem) => {
    const raw = quota.usagePercentage
    if (raw === null || raw === undefined) return undefined
    const value = Number(raw)
    if (!Number.isFinite(value)) return undefined
    return Math.min(Math.max(value, 0), 100)
  }

  const calculatePercentage = (used: number, max?: number | null) => {
    if (!max || max <= 0) return 0
    return Math.min(Math.round((used / max) * 100), 100)
  }

  const getProgressStatus = (used: number, max?: number | null) => {
    if (!max || max <= 0) return undefined
    const percentage = (used / max) * 100
    if (percentage >= 90) return 'exception'
    if (percentage >= 70) return 'warning'
    return 'success'
  }

  const formatQuota = (value?: number | null) => {
    if (value === null || value === undefined || value <= 0)
      return t('subscription.detail.unlimited')
    return value.toString()
  }

  // 7. 获取配额单位
  const getQuotaUnit = (quotaType: number) => {
    // TenantQuotaType: 0=Store, 1=Account, 2=StorageGb, 3=SmsCredits, 4=DeliveryOrders
    switch (quotaType) {
      case 2:
        return 'GB'
      default:
        return ''
    }
  }

  const getQuotaName = (quotaType: number) => {
    switch (quotaType) {
      case 0:
        return t('subscription.detail.stores')
      case 1:
        return t('subscription.detail.accounts')
      case 2:
        return t('subscription.detail.storage')
      case 3:
        return t('subscription.detail.sms')
      case 4:
        return t('subscription.detail.deliveryOrders')
      case 5:
        return t('subscription.detail.promotionSlots')
      default:
        return t('subscription.detail.changeType.unknown')
    }
  }

  // 8. 日期格式化
  const formatDate = (date?: string) => {
    if (!date) return '-'
    return new Date(date).toLocaleDateString()
  }

  const formatDateTime = (date?: string) => {
    if (!date) return '-'
    return new Date(date).toLocaleString()
  }

  type HistoryItem = Api.Subscription.SubscriptionDetailDto['changeHistory'][number] &
    Record<string, any>

  const getHistoryChangeTypeText = (changeType: unknown) => {
    const value = typeof changeType === 'number' ? changeType : Number(changeType)
    switch (value) {
      case 0:
        return t('subscription.detail.changeType.new')
      case 1:
        return t('subscription.detail.changeType.renew')
      case 2:
        return t('subscription.detail.changeType.upgrade')
      case 3:
        return t('subscription.detail.changeType.downgrade')
      default:
        return t('subscription.detail.changeType.unknown')
    }
  }

  const getHistoryTitle = (item: HistoryItem) => {
    const changeTypeText = getHistoryChangeTypeText(item.changeType)
    const fromName = item.fromPackageName ?? item.previousPackageName ?? ''
    const toName = item.toPackageName ?? item.newPackageName ?? ''

    if (fromName && toName && fromName !== toName) {
      return `${changeTypeText}: ${fromName} → ${toName}`
    }

    if (toName) {
      return `${changeTypeText}: ${toName}`
    }

    return changeTypeText
  }

  defineExpose({ open })
</script>

<style scoped>
  .drawer-content {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .card-header {
    display: flex;
    gap: 8px;
    align-items: center;
    font-weight: 600;
  }

  .header-icon {
    font-size: 18px;
    color: var(--el-color-primary);
  }

  .info-card,
  .notes-card,
  .quota-card,
  .history-card {
    margin-bottom: 0;
  }

  .notes-header {
    justify-content: space-between;
  }

  .notes-title {
    display: flex;
    gap: 8px;
    align-items: center;
  }

  .info-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid var(--el-border-color-lighter);
  }

  .info-item:last-child {
    border-bottom: none;
  }

  .info-item .label {
    flex: 0 0 140px;
    font-weight: 500;
    color: var(--el-text-color-secondary);
  }

  .info-item .value {
    flex: 1;
    color: var(--el-text-color-primary);
  }

  .auto-renew-wrap {
    display: flex;
    gap: 12px;
    align-items: center;
  }

  .quota-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .quota-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .quota-label {
    font-weight: 500;
    color: var(--el-text-color-primary);
  }

  .quota-text {
    font-size: 13px;
    color: var(--el-text-color-secondary);
    text-align: right;
  }

  .history-item {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .history-title {
    font-weight: 500;
    color: var(--el-text-color-primary);
  }

  .history-description {
    font-size: 13px;
    color: var(--el-text-color-secondary);
  }
</style>
