import { useEffect, useState } from 'react'

interface LicenseCheckResult {
  isValid: boolean
  isLoading: boolean
  error?: string
}

// License kontrolü için hook
export function useLicenseCheck(): LicenseCheckResult {
  const [isValid, setIsValid] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string>()

  useEffect(() => {
    async function checkLicense() {
      try {
        // Önce localStorage'dan kontrol et
        const cachedLicense = localStorage.getItem('moonui_pro_license')
        if (cachedLicense) {
          const parsed = JSON.parse(cachedLicense)
          if (parsed.expiresAt && new Date(parsed.expiresAt) > new Date()) {
            setIsValid(true)
            setIsLoading(false)
            return
          }
        }

        // API'den kontrol et
        const response = await fetch('/api/license/verify', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            key: process.env.NEXT_PUBLIC_MOONUI_LICENSE_KEY || localStorage.getItem('moonui_license_key')
          })
        })

        if (response.ok) {
          const data = await response.json()
          if (data.valid) {
            // Cache'e kaydet
            localStorage.setItem('moonui_pro_license', JSON.stringify({
              valid: true,
              expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000) // 24 saat
            }))
            setIsValid(true)
          } else {
            setError('Invalid license key')
          }
        } else {
          setError('License verification failed')
        }
      } catch (err) {
        console.error('License check error:', err)
        setError('License verification error')
      } finally {
        setIsLoading(false)
      }
    }

    checkLicense()
  }, [])

  return { isValid, isLoading, error }
}