import { useEffect, useState, type FormEvent } from 'react'
import { updateUser } from '@netlify/identity'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useIdentity } from '@/components/IdentityProvider'

// Handles the callbacks that arrive from Identity emails (confirmation, email
// change and password recovery) wherever the visitor lands.
export function RecoveryDialog() {
  const { callback, clearCallback } = useIdentity()
  const [pending, setPending] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (callback?.type === 'confirmation') {
      toast.success('Email confirmed. Welcome to AkotoCreative SMS!')
      clearCallback()
    } else if (callback?.type === 'email_change') {
      toast.success(`Email updated. You now sign in with ${callback.user?.email ?? 'your new address'}.`)
      clearCallback()
    }
  }, [callback, clearCallback])

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const password = String(new FormData(event.currentTarget).get('password'))
    setPending(true)
    setError(null)
    try {
      await updateUser({ password })
      toast.success('Password updated.')
      clearCallback()
    } catch {
      setError('We could not update your password. Use at least 8 characters and try again.')
    } finally {
      setPending(false)
    }
  }

  return (
    <Dialog open={callback?.type === 'recovery'} onOpenChange={(open) => !open && clearCallback()}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Choose a new password</DialogTitle>
          <DialogDescription>Enter a new password for your AkotoCreative SMS account.</DialogDescription>
        </DialogHeader>
        <form onSubmit={submit} className="grid gap-4">
          <div className="grid gap-2">
            <Label htmlFor="new-password">New password</Label>
            <Input id="new-password" name="password" type="password" minLength={8} required autoComplete="new-password" />
          </div>
          {error && (
            <p role="alert" className="text-sm text-destructive">
              {error}
            </p>
          )}
          <Button type="submit" disabled={pending}>
            {pending ? 'Saving…' : 'Save password'}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  )
}
