import { ref, computed, watch } from 'vue'
import {
  getBoostResidueTimes,
  getGoldCoinProductState,
  ProductionPlayIncreaseInterface,
  startCoinGame,
  UserCenter,
} from '@/service/index/foo'

const TWELVE_HOURS = 12 * 60 * 60 // 12 hours in seconds
const REFRESH_INTERVAL = 10 // 10 seconds

export const useGameTimer = () => {
  const currentLibaoData = ref<UserCenter>({} as UserCenter)
  const playData = ref<ProductionPlayIncreaseInterface>({} as ProductionPlayIncreaseInterface)
  const displayTime = ref('00h 00m 00s')
  const gamePlayTime = ref('00h 00m 00s')
  const percentage = ref(0)
  const isAnimating = ref(false)

  let countdownTimer: number | null = null
  let refreshTimer: number | null = null
  let playTimer: number | null = null

  const libaoShow = computed(() => {
    return currentLibaoData.value.status === 0 || currentLibaoData.value.status === 2
  })

  const formatDisplayTime = (seconds: number): string => {
    if (
      !seconds ||
      isNaN(seconds) ||
      seconds <= 0 ||
      currentLibaoData.value.status === 0 ||
      currentLibaoData.value.status === 2
    ) {
      return '00h 00m 00s'
    }
    seconds = Math.min(seconds, TWELVE_HOURS)
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const remainingSecs = Math.round(seconds % 60)

    return `${hours.toString().padStart(2, '0')}h ${minutes.toString().padStart(2, '0')}m ${remainingSecs.toString().padStart(2, '0')}s`
  }

  const updateTimerAndProgress = () => {
    if (currentLibaoData.value.status === 1 && currentLibaoData.value.residueTimestamp > 0) {
      currentLibaoData.value.residueTimestamp--
      displayTime.value = formatDisplayTime(currentLibaoData.value.residueTimestamp)
      percentage.value =
        ((TWELVE_HOURS - currentLibaoData.value.residueTimestamp) / TWELVE_HOURS) * 100
      isAnimating.value = false
    } else if (currentLibaoData.value.status === 0 || currentLibaoData.value.status === 2) {
      displayTime.value = '00h 00m 00s'
      percentage.value = currentLibaoData.value.status === 2 ? 100 : 0
      isAnimating.value = true
    } else {
      stopTimers()
      refreshGameState()
    }
  }
  const updateGamePlayTime = async () => {
    if (!playData.value.temporaryRate) {
      gamePlayTime.value = '00h 00m 00s'
    }
    if (playData.value.boostResidueTimestamp > 0) {
      playData.value.boostResidueTimestamp--
      gamePlayTime.value = formatDisplayTime(playData.value.boostResidueTimestamp)
    } else {
      gamePlayTime.value = '00h 00m 00s'
      clearInterval(playTimer)
    }
  }
  const initPlayGame = async () => {
    const { data } = await getBoostResidueTimes()
    playData.value = data
  }
  const refreshGameState = async () => {
    try {
      const { data } = await getGoldCoinProductState()
      currentLibaoData.value = data
      if (currentLibaoData.value.status === 1) {
        startTimers()
        isAnimating.value = false
      } else if (currentLibaoData.value.status === 0 || currentLibaoData.value.status === 2) {
        displayTime.value = '00h 00m 00s'
        percentage.value = currentLibaoData.value.status === 2 ? 100 : 0
        isAnimating.value = true
        stopTimers()
      } else {
        stopTimers()
        percentage.value = 0
        isAnimating.value = false
      }
      await initPlayGame()
    } catch (error) {
      console.error('Failed to refresh game state:', error)
    }
  }

  const startTimers = () => {
    stopTimers() // Ensure any existing timers are stopped
    countdownTimer = setInterval(updateTimerAndProgress, 1000)
    refreshTimer = setInterval(refreshGameState, REFRESH_INTERVAL * 1000)
    playTimer = setInterval(updateGamePlayTime, 1000)
  }

  const stopTimers = () => {
    if (countdownTimer) {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
    if (playTimer) {
      clearInterval(playTimer)
      playTimer = null
    }
  }

  const restartGame = async () => {
    try {
      // 调用后端 API 来重新开始游戏
      await startCoinGame()
      // 重新获取游戏状态
      await refreshGameState()
    } catch (error) {
      console.error('Failed to restart game:', error)
      // 这里可以添加错误处理逻辑，比如显示一个错误通知
    }
  }

  watch(
    () => currentLibaoData.value.status,
    (newStatus) => {
      if (newStatus === 1) {
        startTimers()
        isAnimating.value = false
      } else if (newStatus === 0 || newStatus === 2) {
        stopTimers()
        percentage.value = newStatus === 2 ? 100 : 0
        displayTime.value = '00h 00m 00s'
        isAnimating.value = true
      } else {
        stopTimers()
        percentage.value = 0
        isAnimating.value = false
      }
    },
  )

  return {
    currentLibaoData,
    displayTime,
    percentage,
    isAnimating,
    libaoShow,
    refreshGameState,
    stopTimers,
    restartGame,
    gamePlayTime,
    playData,
  }
}
