import type { FC } from 'react';
import React, { useRef, useState } from 'react';
import { Button, Field, Form } from '@theorchard/suite-components';
import { useAppConfig } from '@theorchard/suite-config';
import { formatMessage } from '@theorchard/suite-i18n';
import cx from 'classnames';
import { AUTH0_CONNECTION, CLASSNAME } from './constants';

export const ResetPasswordForm: FC = () => {
    const config = useAppConfig();
    const emailInput = useRef<HTMLInputElement>(null);
    const [passwordReset, setPasswordReset] = useState(false);
    const [wasValidated, setWasValidated] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);

    const handleResetPassword = async () => {
        if (!emailInput.current) return;

        setWasValidated(true);

        if (!emailInput.current.checkValidity()) return;

        setIsSubmitting(true);
        try {
            const response = await fetch(
                `https://${config.auth0Domain}/dbconnections/change_password`,
                {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        email: emailInput.current.value,
                        connection: AUTH0_CONNECTION,
                        client_id: config.auth0ClientId,
                        organization: config.auth0OrgId,
                    }),
                }
            );
            if (response.ok) setPasswordReset(true);
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <div className={`${CLASSNAME}-reset-form`}>
            {passwordReset ? (
                <h4>{formatMessage('error_followLink')}</h4>
            ) : (
                <>
                    <Field
                        className={cx({ 'was-validated': wasValidated })}
                        controlId="reset-email"
                        labelText={formatMessage('account_email')}
                    >
                        <Form.Control
                            type="email"
                            required
                            placeholder="name.surname@email.com"
                            disabled={isSubmitting}
                            className={`${CLASSNAME}-input was-validated`}
                            ref={emailInput}
                        />
                    </Field>
                    <Button
                        onClick={handleResetPassword}
                        disabled={isSubmitting}
                        variant="primary"
                        size="lg"
                    >
                        {formatMessage('account_resetPassword')}
                    </Button>
                </>
            )}
        </div>
    );
};
