import { Anchor } from '@pikku/mantine/core'
import { Link, useNavigate } from '@tanstack/react-router'
import { useState, type FormEvent } from 'react'
import type { I18nString } from '@pikku/react'
import { m } from '@/i18n/messages'
import { useLocale } from '@/i18n/config'
import { AuthCard } from '@/components/AuthCard'
import { EMAIL_IN_USE, registerWithPassword } from '@/lib/auth'

export function SignupPage() {
  useLocale()
  const navigate = useNavigate()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<I18nString | null>(null)

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

    try {
      await registerWithPassword(email, password, { redirectPath: '/app' })
      await navigate({ to: '/app' })
    } catch (err) {
      setError(
        err instanceof Error && err.message === EMAIL_IN_USE
          ? m.auth__signup__email_in_use()
          : m.auth__signup__error(),
      )
    } finally {
      setBusy(false)
    }
  }

  return (
    <AuthCard
      title={m.auth__signup__title()}
      description={m.auth__signup__description()}
      cta={m.auth__signup__cta()}
      email={email}
      password={password}
      passwordAutoComplete="new-password"
      busy={busy}
      message={null}
      error={error}
      onEmailChange={setEmail}
      onPasswordChange={setPassword}
      onSubmit={handleSubmit}
      footer={
        <>
          {m.auth__signup__footer_prompt()}{' '}
          <Anchor component={Link} to="/login">
            {m.auth__signup__footer_action()}
          </Anchor>
        </>
      }
    />
  )
}
