import { getCookie, setCookie } from "@insite/client-framework/Common/Cookies";
import { createHandlerChainRunner, Handler, HasOnSuccess } from "@insite/client-framework/HandlerCreator";
import siteMessage from "@insite/client-framework/SiteMessage";
import ReCAPTCHA from "react-google-recaptcha";

type HandlerType = Handler<
    { location: string; recaptchaRef: React.RefObject<ReCAPTCHA | null> } & HasOnSuccess<boolean>,
    { errorMessage: string }
>;

export const Validate: HandlerType = props => {
    const grecaptcha = (window as { [key: string]: any })["grecaptcha"];
    if (grecaptcha === undefined) {
        return;
    }

    if (!props.parameter.recaptchaRef.current) {
        return;
    }

    if (getCookie("g-recaptcha-verified")) {
        return;
    }

    const reCaptchaResponse = props.parameter.recaptchaRef.current.getValue() || "";
    setCookie("g-recaptcha-response", reCaptchaResponse);

    props.errorMessage = reCaptchaResponse ? "" : (siteMessage("ReCaptcha_RequiredErrorMessage") as string);
    props.dispatch({
        type: "Components/ReCaptcha/SetErrorMessage",
        errorMessage: props.errorMessage,
        location: props.parameter.location,
    });
};

export const ExecuteOnSuccessCallback: HandlerType = props => {
    props.parameter.onSuccess?.(!props.errorMessage);
};

export const chain = [Validate, ExecuteOnSuccessCallback];

const validateReCaptcha = createHandlerChainRunner(chain, "ValidateReCaptcha");
export default validateReCaptcha;
