import { Mail } from 'lucide-react'
import { useState, type FormEvent } from 'react'
import { Link } from 'react-router-dom'

import { AuthLayout } from './AuthLayout'
import { Alert, Button, Input } from '@/components/ui'
import { ApiError, api } from '@/lib/api'

export function ForgotPasswordPage() {
  const [email, setEmail] = useState('')
  const [sentMessage, setSentMessage] = useState<string | null>(null)
  const [error, setError] = useState<ApiError | null>(null)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const handleSubmit = async (event: FormEvent) => {
    event.preventDefault()
    setError(null)
    setIsSubmitting(true)

    try {
      const response = await api.post<{ message: string }>('/auth/forgot-password', { email })
      setSentMessage(response.message)
    } catch (caught) {
      if (caught instanceof ApiError) {
        setError(caught)
      } else {
        throw caught
      }
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <AuthLayout
      title="Reset your password"
      description="We will email you a link to choose a new one."
      footer={
        <Link to="/login" className="font-medium text-text-accent underline underline-offset-4">
          Back to sign in
        </Link>
      }
    >
      {sentMessage !== null ? (
        /*
          The confirmation deliberately does not say whether an account exists
          for that address. A differentiated message here would let anyone test
          whether a given person has a domain portfolio on the platform.
        */
        <Alert tone="success" title="Check your inbox">
          {sentMessage}
        </Alert>
      ) : (
        <form onSubmit={handleSubmit} className="flex flex-col gap-4" noValidate>
          {error !== null && !error.isValidation && (
            <Alert tone="error" title={error.isThrottled ? 'Too many requests' : 'Cannot continue'}>
              {error.message}
            </Alert>
          )}

          <Input
            label="Email address"
            type="email"
            value={email}
            onChange={(event) => setEmail(event.target.value)}
            autoComplete="email"
            autoFocus
            required
            leadingIcon={<Mail className="size-4" />}
            error={error?.errorFor('email')}
          />

          <Button type="submit" size="lg" fullWidth isLoading={isSubmitting}>
            Send reset link
          </Button>
        </form>
      )}
    </AuthLayout>
  )
}
