import { ref, computed, onUnmounted, type Ref } from 'vue'

// 定义参数类型
interface CountdownOptions {
  initialTime: number
  autoStart?: boolean
  onEnd?: () => void
}

// 定义返回类型接口
interface UseCountdown {
  timeLeft: Ref<number>
  formattedTime: Ref<string>
  isRunning: Ref<boolean>
  start: () => void
  stop: () => void
  reset: (newTime?: number) => void
}

export function useCountdown({ initialTime = 0, autoStart = false, onEnd }: CountdownOptions): UseCountdown {
  const timeLeft = ref(initialTime) // 剩余时间（秒）
  const isRunning = ref(false) // 是否在倒计时
  let timer: number | null = null

  // 格式化为 分钟:秒
  const formattedTime = computed(() => {
    const minutes = Math.floor(timeLeft.value / 60)
      .toString()
      .padStart(2, '0')
    const seconds = (timeLeft.value % 60).toString().padStart(2, '0')
    return `${minutes}:${seconds}`
  })

  // 开始倒计时
  const start = () => {
    if (isRunning.value || timeLeft.value <= 0) return
    isRunning.value = true
    timer = window.setInterval(() => {
      if (timeLeft.value > 0) {
        timeLeft.value--
      } else {
        stop()
        if (onEnd) onEnd() // 倒计时结束后调用回调函数
      }
    }, 1000)
  }

  // 停止倒计时
  const stop = () => {
    isRunning.value = false
    if (timer !== null) {
      clearInterval(timer)
      timer = null
    }
  }

  // 重置倒计时
  const reset = (newTime: number = initialTime) => {
    stop()
    timeLeft.value = newTime
    start()
  }

  // 组件卸载时清除定时器
  onUnmounted(() => {
    stop()
  })

  if (autoStart) start() // 自动开始倒计时

  return {
    timeLeft,
    formattedTime,
    isRunning,
    start,
    stop,
    reset,
  }
}
