<template>
  <ElTimeline>
    <ElTimelineItem
      v-for="item in timelineItems"
      :key="item.key"
      :timestamp="item.timestamp"
      :type="item.type"
      placement="top"
    >
      <div class="flex flex-col gap-1">
        <div class="font-medium">{{ item.title }}</div>
        <div v-if="item.description" class="text-sm text-[var(--el-text-color-secondary)]">
          {{ item.description }}
        </div>
      </div>
    </ElTimelineItem>
  </ElTimeline>
</template>

<script setup lang="ts">
  import { computed } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElTimeline, ElTimelineItem } from 'element-plus'
  import { TenantBillingStatus, TenantPaymentStatus } from '@/enums/Billing'
  import { calculateDaysOverdue, formatBillingStatus, formatPaymentMethod } from '@/utils/billing'

  defineOptions({ name: 'BillingTimeline' })

  type TimelineType = 'primary' | 'success' | 'warning' | 'danger' | 'info'

  interface Props {
    /** 账单（列表或详情均可） */
    billing: Api.Billing.BillingListDto | Api.Billing.BillingDetailDto
    /** 支付记录（可选，默认从 billing.payments 读取） */
    payments?: Api.Billing.PaymentRecordDto[]
  }

  const props = defineProps<Props>()
  const { t, locale } = useI18n()

  const formatDateTime = (date?: string) => {
    if (!date) return '-'
    const d = new Date(date)
    if (Number.isNaN(d.getTime())) return '-'
    return d.toLocaleString(locale.value)
  }

  const toTime = (date?: string) => {
    if (!date) return 0
    const d = new Date(date)
    return Number.isNaN(d.getTime()) ? 0 : d.getTime()
  }

  const timelineItems = computed(() => {
    const items: Array<{
      key: string
      timestamp: string
      title: string
      description?: string
      type: TimelineType
      timeValue: number
    }> = []

    // 1. 创建事件
    items.push({
      key: `created-${props.billing.id}`,
      timestamp: formatDateTime(props.billing.createdAt),
      title: t('billing.timeline.created'),
      type: 'info',
      timeValue: toTime(props.billing.createdAt)
    })

    // 2. 到期事件（带逾期天数）
    const days = calculateDaysOverdue(props.billing.dueDate)
    const isOverdue = days > 0
    items.push({
      key: `due-${props.billing.id}`,
      timestamp: formatDateTime(props.billing.dueDate),
      title: t('billing.timeline.dueDate'),
      description: isOverdue ? t('billing.timeline.overdueByDays', { days }) : undefined,
      type: isOverdue ? 'danger' : 'warning',
      timeValue: toTime(props.billing.dueDate)
    })

    // 3. 支付记录事件
    const payments =
      props.payments || (props.billing as Api.Billing.BillingDetailDto).payments || []
    payments.forEach((p) => {
      const at = p.paidAt || p.createdAt
      const isSuccess = p.status === TenantPaymentStatus.Success
      const type: TimelineType = isSuccess
        ? 'success'
        : p.status === TenantPaymentStatus.Failed
          ? 'danger'
          : 'warning'

      items.push({
        key: `payment-${p.id}`,
        timestamp: formatDateTime(at),
        title: t('billing.timeline.payment'),
        description: t('billing.timeline.paymentDesc', {
          amount: Number.isFinite(p.amount) ? p.amount.toFixed(2) : '0.00',
          method: formatPaymentMethod(p.method)
        }),
        type,
        timeValue: toTime(at)
      })
    })

    // 4. 当前状态事件（仅展示一次，避免与 payment 重复过多）
    const statusTypeMap: Record<number, TimelineType> = {
      [TenantBillingStatus.Pending]: 'warning',
      [TenantBillingStatus.Paid]: 'success',
      [TenantBillingStatus.Overdue]: 'danger',
      [TenantBillingStatus.Cancelled]: 'info'
    }

    items.push({
      key: `status-${props.billing.id}`,
      timestamp: formatDateTime(props.billing.updatedAt || props.billing.createdAt),
      title: t('billing.timeline.currentStatus', {
        status: formatBillingStatus(props.billing.status)
      }),
      description: t('billing.timeline.currentStatusDesc'),
      type: statusTypeMap[props.billing.status] || 'info',
      timeValue: toTime(props.billing.updatedAt || props.billing.createdAt)
    })

    // 5. 按时间排序
    return items.sort((a, b) => a.timeValue - b.timeValue)
  })
</script>
