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

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

  const handleSubmit = async (event) => {
    event.preventDefault()
    setError('')
    setLoading(true)
    try {
      await registerUser({ email, username, plainPassword })
      navigate('/login')
    } 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">Create account</Card.Title>
          <Card.Text className="bb-muted">
            Register with an email and a unique username.
          </Card.Text>
          {error && <p className="text-danger">{error}</p>}
          <Form onSubmit={handleSubmit}>
            <Form.Group className="mb-3">
              <Form.Label>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>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>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 ? 'Registering...' : 'Create account'}
            </Button>
          </Form>
        </Card.Body>
      </Card>
    </Container>
  )
}
