import HCaptcha from "@hcaptcha/react-hcaptcha";
import { observer } from "mobx-react-lite";

import styles from "../Login.module.scss";
import { Text } from "preact-i18n";
import { useEffect } from "preact/hooks";

import { useApplicationState } from "../../../mobx/State";

import Preloader from "../../../components/ui/Preloader";

export interface CaptchaProps {
    onSuccess: (token?: string) => void;
    onCancel: () => void;
}

export const CaptchaBlock = observer((props: CaptchaProps) => {
    const configuration = useApplicationState().config.get();

    useEffect(() => {
        if (!configuration?.features.captcha.enabled) {
            props.onSuccess();
        }
    }, [configuration?.features.captcha.enabled, props]);

    if (!configuration?.features.captcha.enabled)
        return <Preloader type="spinner" />;

    return (
        <div>
            <HCaptcha
                sitekey={configuration.features.captcha.key}
                onVerify={(token) => props.onSuccess(token)}
            />
            <div className={styles.footer}>
                <a onClick={props.onCancel}>
                    <Text id="login.cancel" />
                </a>
            </div>
        </div>
    );
});
