import { useState, useEffect } from 'react'
import { AlertTriangle, X, Loader2 } from 'lucide-react'
import { authApi } from '@/api/auth'
import { useAuthStore } from '@/store/authStore'
import { cn } from '@/lib/utils'
import { toast } from '@/lib/toast'

export function EmailVerificationBanner() {
  const user = useAuthStore((s) => s.user)
  const [dismissed, setDismissed] = useState(false)
  const [isSending, setIsSending] = useState(false)
  const [verificationEnabled, setVerificationEnabled] = useState(true)

  useEffect(() => {
    authApi.getVerificationStatus()
      .then((data) => setVerificationEnabled(data.enabled))
      .catch(() => {})
  }, [])

  if (!user || user.email_verified_at || dismissed || !verificationEnabled) return null

  const handleResend = async () => {
    setIsSending(true)
    try {
      await authApi.sendVerificationEmail()
      toast.success('Verification email sent')
    } catch {
      toast.error('Failed to send verification email')
    } finally {
      setIsSending(false)
    }
  }

  return (
    <div className="flex items-center gap-3 border-b border-amber-400/20 bg-amber-400/5 px-4 py-2 text-sm">
      <AlertTriangle className="h-4 w-4 shrink-0 text-amber-400" />
      <span className="text-amber-200">
        Your email is not verified.
      </span>
      <button
        onClick={handleResend}
        disabled={isSending}
        className={cn(
          'text-amber-400 underline hover:text-amber-300 disabled:opacity-50'
        )}
      >
        {isSending ? <Loader2 className="inline h-3 w-3 animate-spin" /> : 'Resend verification email'}
      </button>
      <button
        onClick={() => setDismissed(true)}
        className="ml-auto text-muted-foreground hover:text-foreground"
      >
        <X className="h-4 w-4" />
      </button>
    </div>
  )
}
