import { computed, onUnmounted, ref, watch } from 'vue'

function formatCountdown(ms) {
  if (ms <= 0) return '00:00'
  const totalSec = Math.floor(ms / 1000)
  const h = Math.floor(totalSec / 3600)
  const m = Math.floor((totalSec % 3600) / 60)
  const s = totalSec % 60
  const pad = (n) => String(n).padStart(2, '0')
  if (h > 0) return `${pad(h)}:${pad(m)}:${pad(s)}`
  return `${pad(m)}:${pad(s)}`
}

/**
 * Live countdown for mengya pending_payment orders with paymentExpiresAt.
 */
export function usePaymentCountdown(orderResult, isMengyaPendingPay) {
  const paymentNowTick = ref(Date.now())
  let intervalId = null

  const stop = () => {
    if (intervalId != null) {
      clearInterval(intervalId)
      intervalId = null
    }
  }

  const start = () => {
    stop()
    const v = orderResult.value
    if (!v?.paymentExpiresAt || v.paymentMethod !== 'mengya' || v.status !== 'pending_payment') return
    paymentNowTick.value = Date.now()
    intervalId = setInterval(() => {
      paymentNowTick.value = Date.now()
    }, 1000)
  }

  const paymentCountdownMs = computed(() => {
    paymentNowTick.value
    const exp = orderResult.value?.paymentExpiresAt
    if (!exp || !isMengyaPendingPay.value) return null
    const end = new Date(exp).getTime()
    if (Number.isNaN(end)) return null
    return Math.max(0, end - Date.now())
  })

  const showPaymentCountdown = computed(
    () => Boolean(orderResult.value?.paymentExpiresAt) && isMengyaPendingPay.value
  )

  const paymentCountdownDisplay = computed(() => {
    const ms = paymentCountdownMs.value
    if (ms === null) return '--:--'
    return formatCountdown(ms)
  })

  const paymentCountdownExpired = computed(() => {
    const ms = paymentCountdownMs.value
    return ms !== null && ms <= 0
  })

  const paymentCountdownUrgent = computed(() => {
    const ms = paymentCountdownMs.value
    return ms !== null && ms > 0 && ms < 60_000
  })

  watch(
    orderResult,
    (v) => {
      if (!v) {
        stop()
        return
      }
      if (v.paymentMethod === 'mengya' && v.status === 'pending_payment') {
        start()
      } else {
        stop()
      }
    },
    { deep: false }
  )

  onUnmounted(stop)

  return {
    paymentCountdownMs,
    showPaymentCountdown,
    paymentCountdownDisplay,
    paymentCountdownExpired,
    paymentCountdownUrgent,
    startPaymentCountdown: start,
    stopPaymentCountdown: stop
  }
}
