import { useState } from 'react'
import { Button, Card, Container, Form } from 'react-bootstrap'
import { useNavigate } from 'react-router-dom'
import { registerUser } from '../api/client'
import { useTranslation } from 'react-i18next'

export default function Register() {
  const navigate = useNavigate()
  const [email, setEmail] = useState('')
  const [username, setUsername] = useState('')
  const [plainPassword, setPlainPassword] = useState('')
  const [error, setError] = useState('')
  const [notice, setNotice] = useState('')
  const [loading, setLoading] = useState(false)
  const { t } = useTranslation()

  const handleSubmit = async (event) => {
    event.preventDefault()
    setError('')
    setNotice('')
    setLoading(true)
    try {
      await registerUser({ email, username, plainPassword })
      setNotice(t('auth.verify_notice'))
      setEmail('')
      setUsername('')
      setPlainPassword('')
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <Container className="py-5">
      <Card className="bb-card mx-auto" style={{ maxWidth: '520px' }}>
        <Card.Body>
          <Card.Title className="mb-3">{t('auth.register_title')}</Card.Title>
          <Card.Text className="bb-muted">{t('auth.register_hint')}</Card.Text>
          {error && <p className="text-danger">{error}</p>}
          {notice && <p className="text-success">{notice}</p>}
          <Form onSubmit={handleSubmit}>
            <Form.Group className="mb-3">
              <Form.Label>{t('form.email')}</Form.Label>
              <Form.Control
                type="email"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
                required
              />
            </Form.Group>
            <Form.Group className="mb-3">
              <Form.Label>{t('form.username')}</Form.Label>
              <Form.Control
                type="text"
                value={username}
                onChange={(event) => setUsername(event.target.value)}
                required
              />
            </Form.Group>
            <Form.Group className="mb-4">
              <Form.Label>{t('form.password')}</Form.Label>
              <Form.Control
                type="password"
                value={plainPassword}
                onChange={(event) => setPlainPassword(event.target.value)}
                minLength={8}
                required
              />
            </Form.Group>
            <Button type="submit" variant="dark" disabled={loading}>
              {loading ? t('form.registering') : t('form.create_account')}
            </Button>
          </Form>
        </Card.Body>
      </Card>
    </Container>
  )
}
