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

const siteKey = import.meta.env.VITE_RECAPTCHA_SITE_KEY

let recaptchaScriptPromise

const loadRecaptchaScript = () => {
  if (window.grecaptcha?.render) return Promise.resolve(window.grecaptcha)
  if (recaptchaScriptPromise) return recaptchaScriptPromise

  recaptchaScriptPromise = new Promise((resolve, reject) => {
    const existingScript = document.querySelector('script[src^="https://www.google.com/recaptcha/api.js"]')
    if (existingScript) {
      existingScript.addEventListener('load', () => resolve(window.grecaptcha), { once: true })
      existingScript.addEventListener('error', reject, { once: true })
      return
    }

    const script = document.createElement('script')
    script.src = 'https://www.google.com/recaptcha/api.js?render=explicit'
    script.async = true
    script.defer = true
    script.onload = () => resolve(window.grecaptcha)
    script.onerror = reject
    document.head.appendChild(script)
  })

  return recaptchaScriptPromise
}

const RecaptchaPlaceholder = ({ error = '', onVerify, onExpired, resetKey = 0 }) => {
  const containerRef = useRef(null)
  const widgetIdRef = useRef(null)
  const [isReady, setIsReady] = useState(false)
  const [loadError, setLoadError] = useState('')

  useEffect(() => {
    if (!siteKey || !containerRef.current) return undefined

    let isMounted = true

    loadRecaptchaScript()
      .then((grecaptcha) => {
        grecaptcha.ready(() => {
          if (!isMounted || !containerRef.current || widgetIdRef.current !== null) return

          widgetIdRef.current = grecaptcha.render(containerRef.current, {
            sitekey: siteKey,
            callback: (token) => {
              onVerify?.(token)
            },
            'expired-callback': () => {
              onExpired?.()
            },
            'error-callback': () => {
              onExpired?.()
              setLoadError('Security verification could not be completed. Please try again.')
            },
          })
          setIsReady(true)
        })
      })
      .catch(() => {
        if (isMounted) {
          setLoadError('Security verification could not load. Please refresh and try again.')
        }
      })

    return () => {
      isMounted = false
    }
  }, [onExpired, onVerify])

  useEffect(() => {
    if (widgetIdRef.current === null || !window.grecaptcha?.reset) return
    window.grecaptcha.reset(widgetIdRef.current)
  }, [resetKey])

  if (!siteKey) {
    return (
      <div className="rounded-md border border-amber-400 bg-amber-50 px-4 py-3">
        <p className="text-sm font-semibold text-primary-navy">Security verification is not configured.</p>
      </div>
    )
  }

  return (
    <div className={`rounded-md border bg-background px-4 py-3 ${error || loadError ? 'border-red-500' : 'border-border'}`}>
      <div ref={containerRef} />
      {!isReady && !loadError && <p className="text-sm text-soft-text">Loading security verification...</p>}
      {(error || loadError) && <p className="mt-2 text-xs text-red-500">{error || loadError}</p>}
    </div>
  )
}

export default RecaptchaPlaceholder
