'use client'

import { useState, useSyncExternalStore } from 'react'
import { Button } from '@/components/ui/button'
import { recaptchaToken } from '@/lib/security/recaptcha-client'

const configured = !!(process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY && process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY)

export function GoogleAuthButton({ mode, role, company, next }: {
  mode: 'login' | 'signup'
  role?: 'broker' | 'dispatcher' | 'driver'
  company?: string
  next?: string
}) {
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)
  async function start() {
    if (!configured) return
    setBusy(true)
    setError(null)
    try {
      const captchaToken = await recaptchaToken(mode === 'signup' ? 'google_signup' : 'google_login')
      const response = await fetch('/api/auth/google/start', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ mode, role, company, next, captchaToken }),
      })
      const body = await response.json() as { url?: string; error?: string }
      if (!response.ok || !body.url) throw new Error(body.error || 'Could not start Google sign-in.')
      window.location.assign(body.url)
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : 'Could not start Google sign-in.')
      setBusy(false)
    }
  }

  return (
    <div className="space-y-2">
      <Button type="button" variant="outline" className="w-full" disabled={busy || !configured} onClick={start}>
        {busy ? 'Connecting to Google…' : mode === 'signup' ? 'Create account with Google' : 'Continue with Google'}
      </Button>
      {!configured && <p className="text-center text-xs text-neutral-500">Google sign-in is temporarily unavailable.</p>}
      {error && <p className="text-sm text-red-600" role="alert">{error}</p>}
    </div>
  )
}

const messages: Record<string, string> = {
  expired: 'The Google sign-in attempt expired. Please try again.',
  cancelled: 'Google sign-in was cancelled. Please try again.',
  verification: 'Google could not verify this sign-in. Please try again.',
  no_account: 'No account is linked to that Google address. Choose your role and create one below.',
  blocked: 'This account is blocked. Contact support.',
  admin: 'Admin accounts must use the existing sign-in method.',
  account: 'Could not prepare your account. Please try again.',
  linked: 'This account is already linked to another Google sign-in. Contact support.',
  unavailable: 'Google sign-in is temporarily unavailable. Please try again.',
}

export function GoogleAuthError() {
  const search = useSyncExternalStore(() => () => {}, () => window.location.search, () => '')
  const reason = new URLSearchParams(search).get('google_error')
  const message = reason ? messages[reason] ?? null : null
  return message ? <p className="rounded-lg bg-red-50 p-3 text-sm text-red-700" role="alert">{message}</p> : null
}
