import { useState } from 'react'
import { Button, Card, Container, Form } from 'react-bootstrap'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import { useTranslation } from 'react-i18next'

export default function Login() {
    const { login } = useAuth()
    const navigate = useNavigate()
    const [loginValue, setLoginValue] = useState('')
    const [password, setPassword] = useState('')
    const [error, setError] = useState('')
    const [loading, setLoading] = useState(false)
    const { t } = useTranslation()

    const handleSubmit = async (event) => {
        event.preventDefault()
        setError('')
        setLoading(true)
        try {
            await login(loginValue, password)
            navigate('/')
        } catch (err) {
            setError(err.message)
        } finally {
            setLoading(false)
        }
    }

    return (
        <Container fluid className="py-5">
            <Card className="bb-card mx-auto" style={{ maxWidth: '480px' }}>
                <Card.Body>
                    <Card.Title className="mb-3">{t('auth.login_title')}</Card.Title>
                    <Card.Text className="bb-muted">{t('auth.login_hint')}</Card.Text>
                    {error && <p className="text-danger">{error}</p>}
                    <Form onSubmit={handleSubmit}>
                        <Form.Group className="mb-3">
                            <Form.Label>{t('auth.login_identifier')}</Form.Label>
                            <Form.Control
                                type="text"
                                value={loginValue}
                                onChange={(event) => setLoginValue(event.target.value)}
                                placeholder={t('auth.login_placeholder')}
                                required
                            />
                        </Form.Group>
                        <Form.Group className="mb-4">
                            <Form.Label>{t('form.password')}</Form.Label>
                            <Form.Control
                                type="password"
                                value={password}
                                onChange={(event) => setPassword(event.target.value)}
                                required
                            />
                        </Form.Group>
                        <Button type="submit" variant="dark" disabled={loading}>
                            {loading ? t('form.signing_in') : t('form.sign_in')}
                        </Button>
                    </Form>
                </Card.Body>
            </Card>
        </Container>
    )
}
