import { ref } from 'vue'
import * as statsApi from '@/api/stats'
import type {
  StatsHomeScreenQueryData,
  StatsHomeScreenFallHistory,
  StatsHomeScreenAlarmHistory,
} from '@/api/stats/types'

export function useDashboardPolling(options: { tenantId: string }) {
  const todayScreenData = ref<StatsHomeScreenQueryData | null>(null)
  const fallHistoryData = ref<StatsHomeScreenFallHistory | null>(null)
  const alarmHistoryData = ref<StatsHomeScreenAlarmHistory | null>(null)

  const fallQueryType = ref<'day' | 'month'>('day')
  const alarmQueryType = ref<'day' | 'month'>('day')

  let realtimeTimer: ReturnType<typeof setInterval> | null = null
  let businessTimer: ReturnType<typeof setInterval> | null = null
  let isVisible = true

  const MAX_RETRY = 3
  let retryCountRealtime = 0
  let retryCountBusiness = 0

  const getTodayData = async () => {
    if (!isVisible) return
    try {
      const res = await statsApi.statsHomeScreenQuery({
        tenantId: options.tenantId,
      })
      todayScreenData.value = res.data
      retryCountRealtime = 0
    } catch {
      retryCountRealtime++
      if (retryCountRealtime < MAX_RETRY) {
        setTimeout(getTodayData, 1000)
      }
    }
  }

  const getHistoryData = async () => {
    if (!isVisible) return
    try {
      const [fallRes, alarmRes] = await Promise.all([
        statsApi.statsHomeScreenFallHistory({
          tenantId: options.tenantId,
          queryType: fallQueryType.value,
        }),
        statsApi.statsHomeScreenAlarmHistory({
          tenantId: options.tenantId,
          queryType: alarmQueryType.value,
        }),
      ])
      fallHistoryData.value = fallRes.data
      alarmHistoryData.value = alarmRes.data
      retryCountBusiness = 0
    } catch {
      retryCountBusiness++
      if (retryCountBusiness < MAX_RETRY) {
        setTimeout(getHistoryData, 2000)
      }
    }
  }

  const start = () => {
    getTodayData()
    getHistoryData()
    realtimeTimer = setInterval(getTodayData, 5000)
    businessTimer = setInterval(getHistoryData, 30000)
    document.addEventListener('visibilitychange', handleVisibilityChange)
  }

  const stop = () => {
    if (realtimeTimer) clearInterval(realtimeTimer)
    if (businessTimer) clearInterval(businessTimer)
    realtimeTimer = null
    businessTimer = null
    document.removeEventListener('visibilitychange', handleVisibilityChange)
  }

  const handleVisibilityChange = () => {
    isVisible = document.visibilityState === 'visible'
    if (isVisible) {
      start()
    } else {
      stop()
    }
  }

  const updateFallQueryType = async (type: 'day' | 'month') => {
    fallQueryType.value = type
    const res = await statsApi.statsHomeScreenFallHistory({
      tenantId: options.tenantId,
      queryType: fallQueryType.value,
    })
    fallHistoryData.value = res.data
  }

  const updateAlarmQueryType = async (type: 'day' | 'month') => {
    alarmQueryType.value = type
    const res = await statsApi.statsHomeScreenAlarmHistory({
      tenantId: options.tenantId,
      queryType: alarmQueryType.value,
    })
    alarmHistoryData.value = res.data
  }

  return {
    todayScreenData,
    fallHistoryData,
    alarmHistoryData,
    updateFallQueryType,
    updateAlarmQueryType,
    start,
    stop,
  }
}
