import { useState, useEffect } from 'react'
import { aiBuilderApi } from '@/api'

const CACHE_TTL_MS = 5 * 60 * 1000

let cachedResult: { aiEnabled: boolean; timestamp: number } | null = null

/** Clear the cached quota (call on logout to prevent stale data across users). */
export function clearCachedQuota() {
  cachedResult = null
}

export function useCachedQuota() {
  const [aiEnabled, setAiEnabled] = useState(cachedResult?.aiEnabled ?? false)
  const [isLoading, setIsLoading] = useState(!cachedResult)

  useEffect(() => {
    if (cachedResult && Date.now() - cachedResult.timestamp < CACHE_TTL_MS) {
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setAiEnabled(cachedResult.aiEnabled)
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setIsLoading(false)
      return
    }

    setIsLoading(true)
    aiBuilderApi
      .getQuota()
      .then((q) => {
        cachedResult = { aiEnabled: q.ai_enabled, timestamp: Date.now() }
        setAiEnabled(q.ai_enabled)
      })
      .catch(() => {})
      .finally(() => setIsLoading(false))
  }, [])

  return { aiEnabled, isLoading }
}
