import { useState, useEffect } from '@wordpress/element'
import apiFetch from '@wordpress/api-fetch'
import { Status, CriticalCSSResponse } from '../types/types'

type WPError = {
  code: string
  message: string
  data?: {
    status?: number
    [key: string]: any
  }
}

export const useStatus = (postId: number | null, activateCriticalCSS: string | boolean) => {
  const [status, setStatus] = useState<Status | null>(null)
  const [loading, setLoading] = useState<boolean>(false)

  const fetchStatus = async () => {
    if (!postId) return
    setLoading(true)

    console.log('Fetching Critical CSS for Post ID:', postId)

    try {
      const response: CriticalCSSResponse = await apiFetch({path: `/easy-critical-css/v1/status/${postId}` })

      // If Critical CSS not activated, override the status to "paused"
      setStatus(activateCriticalCSS ? response.status : 'paused')
    } catch (err: unknown) {
      const wpError = err as WPError
      if (wpError?.code === 'invalid_post_id') {
        setStatus('unavailable');
      } else {
        console.error('Error fetching Critical CSS status:', err)
        setStatus('error')
      }
    }

    setLoading(false)
  }
  
  useEffect(() => {
    fetchStatus()
  }, [postId, activateCriticalCSS])

  return { status, loading, fetchStatus }
}
