import { useEffect, useState } from 'react'
import { Button, Card, Container, Form } from 'react-bootstrap'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { requestPasswordReset, resetPassword } from '../api/client'

export default function ResetPassword() {
    const { t } = useTranslation()
    const navigate = useNavigate()
    const [searchParams] = useSearchParams()
    const token = searchParams.get('token') || ''
    const emailFromLink = searchParams.get('email') || ''
    const isResetFlow = token.length > 0
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [passwordConfirmation, setPasswordConfirmation] = useState('')
    const [error, setError] = useState('')
    const [loading, setLoading] = useState(false)

    useEffect(() => {
        if (emailFromLink) {
            setEmail(emailFromLink)
        }
    }, [emailFromLink])

    const handleSubmit = async (event) => {
        event.preventDefault()
        setError('')
        setLoading(true)
        try {
            if (isResetFlow) {
                await resetPassword({
                    token,
                    email,
                    password,
                    password_confirmation: passwordConfirmation,
                })
                navigate('/login')
            } else {
                await requestPasswordReset(email)
                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">
                        {isResetFlow ? t('auth.reset_password_title') : t('auth.forgot_password')}
                    </Card.Title>
                    <Card.Text className="bb-muted">
                        {isResetFlow ? t('auth.reset_password_hint') : t('auth.forgot_password_hint')}
                    </Card.Text>
                    {error && <p className="text-danger">{error}</p>}
                    <Form onSubmit={handleSubmit}>
                        <Form.Group className="mb-4">
                            <Form.Label>{t('form.email')}</Form.Label>
                            <Form.Control
                                type="email"
                                value={email}
                                onChange={(event) => setEmail(event.target.value)}
                                placeholder={t('auth.reset_email_placeholder')}
                                required
                            />
                        </Form.Group>
                        {isResetFlow && (
                            <>
                                <Form.Group className="mb-3">
                                    <Form.Label>{t('form.password')}</Form.Label>
                                    <Form.Control
                                        type="password"
                                        value={password}
                                        onChange={(event) => setPassword(event.target.value)}
                                        required
                                    />
                                </Form.Group>
                                <Form.Group className="mb-4">
                                    <Form.Label>{t('auth.confirm_password')}</Form.Label>
                                    <Form.Control
                                        type="password"
                                        value={passwordConfirmation}
                                        onChange={(event) => setPasswordConfirmation(event.target.value)}
                                        required
                                    />
                                </Form.Group>
                            </>
                        )}
                        <div className="d-flex w-100 align-items-center gap-2">
                            <Button as={Link} to="/login" type="button" variant="outline-secondary" disabled={loading}>
                                {t('acp.cancel')}
                            </Button>
                            <Button type="submit" className="ms-auto bb-accent-button" disabled={loading}>
                                {loading
                                    ? isResetFlow
                                        ? t('auth.resetting_password')
                                        : t('auth.sending_reset_link')
                                    : isResetFlow
                                      ? t('auth.reset_password_submit')
                                      : t('auth.send_reset_link')}
                            </Button>
                        </div>
                    </Form>
                </Card.Body>
            </Card>
        </Container>
    )
}
