import { useEffect, useState } from 'react'
import { getSettings } from '@netlify/identity'
import { Button } from '@/components/ui/button'
import { startGoogleSignIn } from '@/components/IdentityProvider'

export function GoogleIcon({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 24 24" className={className} aria-hidden>
      <path fill="#4285F4" d="M23.5 12.27c0-.85-.08-1.67-.22-2.45H12v4.64h6.45a5.52 5.52 0 0 1-2.4 3.62v3h3.88c2.27-2.09 3.57-5.17 3.57-8.81Z" />
      <path fill="#34A853" d="M12 24c3.24 0 5.96-1.07 7.94-2.9l-3.88-3.01c-1.07.72-2.45 1.15-4.06 1.15-3.13 0-5.78-2.11-6.72-4.95H1.27v3.11A12 12 0 0 0 12 24Z" />
      <path fill="#FBBC05" d="M5.28 14.29a7.2 7.2 0 0 1 0-4.58V6.6H1.27a12 12 0 0 0 0 10.8l4.01-3.11Z" />
      <path fill="#EA4335" d="M12 4.77c1.76 0 3.34.61 4.59 1.8l3.44-3.44A11.5 11.5 0 0 0 12 0 12 12 0 0 0 1.27 6.6l4.01 3.11C6.22 6.88 8.87 4.77 12 4.77Z" />
    </svg>
  )
}

// `null` while loading. Google only works once it is switched on under
// Identity > External providers in the Netlify project settings.
export function useGoogleAvailable() {
  const [available, setAvailable] = useState<boolean | null>(null)
  useEffect(() => {
    let active = true
    getSettings()
      .then((settings) => active && setAvailable(Boolean(settings.providers.google)))
      .catch(() => active && setAvailable(false))
    return () => {
      active = false
    }
  }, [])
  return available
}

// "Continue with Google" for the sign-in and sign-up forms. Hidden when Google
// isn't switched on for the site. `next` is the page to land on afterwards.
export function GoogleSignInButton({ label, next, divider = true }: { label: string; next?: string; divider?: boolean }) {
  const available = useGoogleAvailable()
  if (!available) return null
  return (
    <>
      <Button type="button" variant="outline" size="lg" className="w-full" onClick={() => startGoogleSignIn(undefined, next)}>
        <GoogleIcon className="size-4" /> {label}
      </Button>
      {divider && <div className="flex items-center gap-3 text-xs text-muted-foreground" aria-hidden>
        <span className="h-px flex-1 bg-border" /> or use your email <span className="h-px flex-1 bg-border" />
      </div>}
    </>
  )
}
