import { getCookie } from "@insite/client-framework/Common/Cookies";
import StyledWrapper from "@insite/client-framework/Common/StyledWrapper";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import resetReCaptcha from "@insite/client-framework/Store/Components/ReCaptcha/Handlers/ResetReCaptcha";
import validateReCaptcha from "@insite/client-framework/Store/Components/ReCaptcha/Handlers/ValidateReCaptcha";
import { getSession, getSettingsCollection } from "@insite/client-framework/Store/Context/ContextSelectors";
import Typography, { TypographyPresentationProps } from "@insite/mobius/Typography";
import InjectableCss from "@insite/mobius/utilities/InjectableCss";
import React, { RefObject, useEffect, useState } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import { connect, ResolveThunks } from "react-redux";
import { css } from "styled-components";

interface OwnProps {
    location: string;
    recaptchaRef: RefObject<ReCAPTCHA>;
}

const mapStateToProps = (state: ApplicationState, { location, recaptchaRef }: OwnProps) => {
    const { websiteSettings } = getSettingsCollection(state);
    const session = getSession(state);
    return {
        siteKey: websiteSettings.reCaptchaSiteKey,
        isEnabled: (websiteSettings as { [key: string]: any })[`reCaptchaEnabledFor${location}`],
        isAuthenticated: session && (session.isAuthenticated || session.rememberMe) && !session.isGuest,
        errorMessage: state.components.reCaptcha.errorMessage[location],
        recaptchaRef,
        location,
    };
};

const mapDispatchToProps = {
    validateReCaptcha,
    resetReCaptcha,
};

type Props = OwnProps & ReturnType<typeof mapStateToProps> & ResolveThunks<typeof mapDispatchToProps>;

export interface ReCaptchaStyles {
    wrapper?: InjectableCss;
    errorMessageText?: TypographyPresentationProps;
}

export const reCaptchaStyles: ReCaptchaStyles = {
    errorMessageText: {
        color: "danger",
        css: css`
            margin-top: 5px;
        `,
    },
};

const styles = reCaptchaStyles;

const ReCaptcha = ({
    siteKey,
    isEnabled,
    isAuthenticated,
    errorMessage,
    recaptchaRef,
    location,
    validateReCaptcha,
    resetReCaptcha,
}: Props) => {
    const [firstRender, setFirstRender] = useState(true);

    useEffect(() => {
        setFirstRender(false);
        resetReCaptcha({ location });
    }, []);

    const handleSuccess = () => {
        validateReCaptcha({ location, recaptchaRef });
    };

    if (firstRender || !isEnabled || isAuthenticated || !!getCookie("g-recaptcha-verified")) {
        return null;
    }

    return (
        <StyledWrapper {...styles.wrapper}>
            <ReCAPTCHA ref={recaptchaRef} sitekey={siteKey} onChange={handleSuccess} />
            {errorMessage && (
                <Typography as="p" {...styles.errorMessageText}>
                    {errorMessage}
                </Typography>
            )}
        </StyledWrapper>
    );
};

export default connect(mapStateToProps, mapDispatchToProps)(ReCaptcha);
