import { onBeforeUnmount, watch, type ComputedRef } from 'vue'

import { useAdminToast } from './useAdminToast'
import { useAwardsStore } from '../stores/awards'

const ADMIN_API_DISCONNECT_TOAST_KEY = 'admin-api-disconnected'
const ADMIN_API_DISCONNECT_MESSAGE =
  'Backend/API nicht erreichbar. Der Admin-Bereich bleibt eingeschränkt, bis die Verbindung wieder da ist.'
const ADMIN_API_DISCONNECT_TOAST_DELAY_MS = 1200
const RECONNECT_PROBE_INTERVAL_MS = 5000

export function useAdminApiDisconnectToast(isAdminRoute: ComputedRef<boolean>) {
  const awardsStore = useAwardsStore()
  const { dismissAdminToast, showAdminToast } = useAdminToast()

  let reconnectTimer: number | undefined
  let disconnectToastTimer: number | undefined
  let reconnectProbeRunning = false

  function clearReconnectTimer() {
    if (reconnectTimer === undefined || typeof window === 'undefined') return
    window.clearTimeout(reconnectTimer)
    reconnectTimer = undefined
  }

  function clearDisconnectToastTimer() {
    if (disconnectToastTimer === undefined || typeof window === 'undefined') return
    window.clearTimeout(disconnectToastTimer)
    disconnectToastTimer = undefined
  }

  function scheduleReconnectProbe() {
    if (reconnectTimer !== undefined || typeof window === 'undefined') return

    reconnectTimer = window.setTimeout(async () => {
      reconnectTimer = undefined
      if (!isAdminRoute.value || awardsStore.apiMode !== 'fallback' || reconnectProbeRunning) return

      reconnectProbeRunning = true
      try {
        await awardsStore.loadDatabaseHealth()
      } catch {
        // Keep the persistent disconnect toast visible until health checks pass again.
      } finally {
        reconnectProbeRunning = false
        if (isAdminRoute.value && awardsStore.apiMode === 'fallback') {
          scheduleReconnectProbe()
        }
      }
    }, RECONNECT_PROBE_INTERVAL_MS)
  }

  function scheduleDisconnectToast() {
    if (disconnectToastTimer !== undefined || typeof window === 'undefined') return

    disconnectToastTimer = window.setTimeout(() => {
      disconnectToastTimer = undefined
      if (!isAdminRoute.value || awardsStore.apiMode !== 'fallback') return

      showAdminToast(ADMIN_API_DISCONNECT_MESSAGE, 'error', {
        key: ADMIN_API_DISCONNECT_TOAST_KEY,
        persistent: true,
      })
    }, ADMIN_API_DISCONNECT_TOAST_DELAY_MS)
  }

  watch(
    () => isAdminRoute.value && awardsStore.apiMode === 'fallback',
    (shouldShowDisconnectToast) => {
      if (shouldShowDisconnectToast) {
        scheduleDisconnectToast()
        scheduleReconnectProbe()
        return
      }

      clearDisconnectToastTimer()
      clearReconnectTimer()
      dismissAdminToast(ADMIN_API_DISCONNECT_TOAST_KEY)
    },
    { immediate: true },
  )

  onBeforeUnmount(() => {
    clearDisconnectToastTimer()
    clearReconnectTimer()
  })
}
