import { useState, useEffect, useCallback } from 'react'

const CACHE_KEY = 'boostbot_update_check'
const CHECK_INTERVAL_MS = 60 * 60 * 1000 // 1 hour

interface CachedUpdateStatus {
  updateAvailable: boolean
  latestVersion: string
  currentVersion: string
  downloadUrl: string
  changelog: string
  releaseDate: string
  lastChecked: number // timestamp
}

/**
 * Hook that checks for plugin updates in the background.
 * Throttled to max once per hour, persisted in localStorage.
 * Used by the Sidebar to show a glow on the Updates tab,
 * and by the Updates page itself.
 */
export function useUpdateCheck() {
  const [updateAvailable, setUpdateAvailable] = useState(false)
  const [latestVersion, setLatestVersion] = useState<string | null>(null)
  const [isChecking, setIsChecking] = useState(false)

  const apiUrl = window.boostbotAdmin?.apiUrl || '/wp-json/boostbot/v1/'
  const nonce = window.boostbotAdmin?.nonce || ''

  // Load cached status on mount
  useEffect(() => {
    const cached = getCachedStatus()
    if (cached) {
      setUpdateAvailable(cached.updateAvailable)
      setLatestVersion(cached.latestVersion)
    }

    // Check if we should fetch fresh data
    if (shouldCheck(cached)) {
      checkForUpdates()
    }
  }, [])

  function getCachedStatus(): CachedUpdateStatus | null {
    try {
      const raw = localStorage.getItem(CACHE_KEY)
      if (!raw) return null
      return JSON.parse(raw)
    } catch {
      return null
    }
  }

  function shouldCheck(cached: CachedUpdateStatus | null): boolean {
    if (!cached) return true
    return Date.now() - cached.lastChecked > CHECK_INTERVAL_MS
  }

  const checkForUpdates = useCallback(async () => {
    setIsChecking(true)
    try {
      const response = await fetch(`${apiUrl}updates/check`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': nonce,
        },
        credentials: 'same-origin',
      })

      if (!response.ok) return

      const data = await response.json()
      const result = data.data || data

      const status: CachedUpdateStatus = {
        updateAvailable: !!result.update_available,
        latestVersion: result.latest_version || '',
        currentVersion: result.current_version || '',
        downloadUrl: result.download_url || '',
        changelog: result.changelog || '',
        releaseDate: result.release_date || '',
        lastChecked: Date.now(),
      }

      localStorage.setItem(CACHE_KEY, JSON.stringify(status))
      setUpdateAvailable(status.updateAvailable)
      setLatestVersion(status.latestVersion)
    } catch {
      // Silently fail - don't disrupt the admin experience
    } finally {
      setIsChecking(false)
    }
  }, [apiUrl, nonce])

  // Clear the cache (e.g., after installing an update)
  const clearCache = useCallback(() => {
    localStorage.removeItem(CACHE_KEY)
    setUpdateAvailable(false)
    setLatestVersion(null)
  }, [])

  return {
    updateAvailable,
    latestVersion,
    isChecking,
    checkForUpdates,
    clearCache,
  }
}
