import React, { useCallback, useMemo, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import DOMPurify from 'dompurify';
import ReCAPTCHA from 'react-google-recaptcha';
import { useForm } from 'react-hook-form';
import Grid from '../../atoms/grid/Grid';
import GridContainer from '../../atoms/grid-container/GridContainer';
import Input from '../../atoms/input/Input';
import CheckboxUncontrolled from '../../atoms/checkbox-uncontrolled/CheckboxUncontrolled';
import Textarea from '../../atoms/textarea/Textarea';
import Select from '../../atoms/select/Select';
import Button from '../../atoms/button/Button';
import Icon from '../../atoms/icon/Icon';
import FormLabel from '../../atoms/form-label/FormLabel';
import Alert, { alertTypes } from '../../atoms/alert/Alert';
import Modal from '../../atoms/modal/Modal';
import { addAlert, ALERT_LEAD_ADD_SUCCESS } from '../../tools/alerts';
import { createPostPayload, getDefaultSelectedOption, sanitizePhoneData,
    getEditionDataFromUrlParams } from '../../tools/components/leadForm';
import { createNamespace } from '../../tools/namingTools';
import { generateUniqueID, getCookieValue } from '../../tools/helpers';
import { useContainerWidth } from '../../tools/widths/useContainerWidth';
import { bMedium } from '../../constants/breakpoints';
import { leadsPropTypes } from '../../constants/prop-types/application/leads';
import { TYPE_TEXTAREA, TYPE_SELECT, TYPE_STYLED_SELECT, TYPE_CHECKBOX, NAME_COUNTRY, NAME_STATE, NAME_PROVINCE } from '../../constants/components/lead-form';
import withListener from '../withListener';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/LeadForm.scss';

const n = createNamespace('Leadform');

const isRecaptchaFlagOn = flagValue => flagValue === true || flagValue === 'true';

const getViewportCenteredModalPosition = () => {
    if (typeof window === 'undefined') {
        return { left: 0, top: 0 };
    }
    return {
        left: Math.round(window.innerWidth / 2),
        top: Math.round(Math.max(24, window.innerHeight * 0.2))
    };
};

const LeadForm = ({
    data: {
        form: {
            actionEndpoint,
            productUrl,
            otherData,
            userAndCompanyInfo,
            schema: {
                firstName,
                lastName,
                email,
                phone,
                phoneExtension,
                companyName,
                companySize,
                street1,
                street2,
                city,
                state,
                province,
                zip,
                country,
                notes,
                custom
            }
        },
        i18n: i18nLeads,
        leadsRecaptchaEnabled,
        recaptchaKeys,
        config
    }
}) => {
    const [currentCountry, setCurrentCountry] = useState(getDefaultSelectedOption(country));
    const [currentState, setCurrentState] = useState(getDefaultSelectedOption(state));
    const [currentProvince, setCurrentProvince] = useState(getDefaultSelectedOption(province));

    const [errorStatus, setErrorStatus] = useState(false);
    const [showRecaptchaModal, setShowRecaptchaModal] = useState(false);
    const [pendingFormData, setPendingFormData] = useState(null);
    const [recaptchaToken, setRecaptchaToken] = useState(null);
    const [recaptchaError, setRecaptchaError] = useState(false);
    const [recaptchaModalPosition, setRecaptchaModalPosition] = useState({ left: 0, top: 0 });
    const [isPostingLead, setIsPostingLead] = useState(false);
    const recaptchaRef = useRef(null);
    const isPostingLeadRef = useRef(false);

    const isLoggedIn = Boolean(config?.user?.isLoggedIn);
    const recaptchaPublicKey = recaptchaKeys?.recaptchaPublicKey || '';
    const isRecaptchaRequired = Boolean(
        isRecaptchaFlagOn(leadsRecaptchaEnabled) && !isLoggedIn && recaptchaPublicKey
    );

    const [containerRef, containerWidth] = useContainerWidth();
    const isMobile = containerWidth && containerWidth < bMedium;
    const columns = isMobile ? 1 : 2;
    const { handleSubmit, register, errors, control } = useForm();

    // since form inputs are uncontrolled, we don't have access to empty their values, so in order
    // to empty them, we just recreate them with a different key when we want to empty them
    // we cannot use html form reset, because some inputs (Selects, Checkboxes) need to be controlled in order
    // to be displayed correctly, as they are not native inputs
    const [currentSession, setSession] = useState(Date.now());
    const resetForm = () => {
        setCurrentCountry(getDefaultSelectedOption(country));
        setCurrentState(getDefaultSelectedOption(state));
        setCurrentProvince(getDefaultSelectedOption(province));
        setSession(Date.now());
    };

    const resetRecaptchaState = () => {
        setRecaptchaToken(null);
        setRecaptchaError(false);
        setPendingFormData(null);
        if (recaptchaRef.current) {
            recaptchaRef.current.reset();
        }
    };

    const closeRecaptchaModal = () => {
        if (isPostingLeadRef.current) {
            return;
        }
        setShowRecaptchaModal(false);
        resetRecaptchaState();
    };

    const getCountryPhoneCode = useMemo(
        () => (
            (currentCountry && currentCountry.phoneCode)
                ? `+${currentCountry.phoneCode}`
                : null),
        [currentCountry]
    );

    const editionData = getEditionDataFromUrlParams();

    const postLead = (formData, token) => {
        if (isPostingLeadRef.current) {
            return;
        }
        isPostingLeadRef.current = true;
        setIsPostingLead(true);
        const payload = createPostPayload(otherData, formData, custom, editionData);
        payload.customer.contact.phone = sanitizePhoneData(formData, getCountryPhoneCode);
        if (token) {
            payload.recaptchaToken = token;
        }
        const payloadString = JSON.stringify(payload);

        const XHR = new XMLHttpRequest();
        const success = [200, 201, 202, 204];

        XHR.addEventListener('load', () => {
            if (success.includes(XHR.status)) {
                resetForm();
                closeRecaptchaModal();
                addAlert(ALERT_LEAD_ADD_SUCCESS);
                window.location.assign(productUrl);
            } else {
                console.error(`Leads API error: ${XHR?.responseText} ${actionEndpoint}`);
                setErrorStatus(true);
                isPostingLeadRef.current = false;
                setIsPostingLead(false);
                resetRecaptchaState();
            }
        });

        XHR.addEventListener('error', () => {
            setErrorStatus(true);
            isPostingLeadRef.current = false;
            setIsPostingLead(false);
            resetRecaptchaState();
        });

        XHR.open('POST', actionEndpoint);
        XHR.setRequestHeader('Content-Type', 'application/json');
        XHR.setRequestHeader('X-XSRF-TOKEN', getCookieValue('XSRF-TOKEN'));
        XHR.send(payloadString);
    };

    const onFormValid = formData => {
        if (isPostingLeadRef.current) {
            return;
        }
        if (isRecaptchaRequired) {
            if (showRecaptchaModal) {
                return;
            }
            setPendingFormData(formData);
            setRecaptchaModalPosition(getViewportCenteredModalPosition());
            setShowRecaptchaModal(true);
            return;
        }
        postLead(formData);
    };

    const onRecaptchaModalSubmit = () => {
        if (isPostingLeadRef.current) {
            return;
        }
        if (!recaptchaToken) {
            setRecaptchaError(true);
            return;
        }
        const formData = pendingFormData;
        const token = recaptchaToken;
        setShowRecaptchaModal(false);
        setRecaptchaToken(null);
        setPendingFormData(null);
        if (recaptchaRef.current) {
            recaptchaRef.current.reset();
        }
        postLead(formData, token);
    };

    const handleRecaptchaChange = token => {
        setRecaptchaToken(token);
        if (token) {
            setRecaptchaError(false);
        }
    };

    const i18nLeadsWithDefaults = { ...LeadForm.defaultProps.data.i18n, ...i18nLeads };

    const closeForm = () => {
        window.location.assign(productUrl);
    };

    const getInputValidationRules = useCallback(
        item => {
            const inputValidationRules = {};

            if (item.isRequired) {
                inputValidationRules.required = {
                    value: item.isRequired,
                    message: i18nLeadsWithDefaults.defaultError
                };
            }

            // Custom message for maxLength error
            if (item.editorAttrs && item.editorAttrs.maxlength) {
                inputValidationRules.maxLength = {
                    value: item.editorAttrs.maxlength,
                    message: i18nLeadsWithDefaults.maxLengthError.replace('{maxLength}', item.editorAttrs.maxlength)
                };

                // For textarea fields, add custom validation to check if over limit
                if (item.type === TYPE_TEXTAREA) {
                    inputValidationRules.validate = value => {
                        if (value && value.length > item.editorAttrs.maxlength) {
                            return i18nLeadsWithDefaults.maxLengthError.replace('{maxLength}', item.editorAttrs.maxlength);
                        }
                        return true;
                    };
                }
            }

            // TODO add custom message for email error
            if (item.validators) {
                item.validators.forEach(validator => {
                    if (validator === 'email') {
                        inputValidationRules.pattern = {
                            value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                            message: i18nLeadsWithDefaults.defaultError
                        };
                    }
                    if (validator === 'arrayRequired') {
                        inputValidationRules.required = {
                            value: item.isRequired,
                            message: i18nLeadsWithDefaults.defaultError
                        };
                    }
                });
            }

            return inputValidationRules;
        },
        [i18nLeadsWithDefaults.defaultError, i18nLeadsWithDefaults.maxLengthError]
    );

    const renderInput = item => {
        if (!item) {
            return null;
        }

        const { name, title, hint, isRequired, type } = item;
        const placeholder = item.editorAttrs && item.editorAttrs.placeholder;
        const errorMessage = errors && errors[name] ? errors[name].message : null;
        const validationRules = getInputValidationRules(item);
        const optionList = item.options && [...item.options];
        const inputKey = generateUniqueID([name, currentSession]);

        let inputUpdateFunc = null;
        let addon = '';
        let addonLabel = '';
        let defaultValue = '';

        if (item.countryCodeValidationField) {
            addon = getCountryPhoneCode;
            addonLabel = i18nLeadsWithDefaults.countryCode;
        }

        switch (name) {
            case NAME_COUNTRY: {
                defaultValue = currentCountry;
                inputUpdateFunc = setCurrentCountry;
                break;
            }
            case NAME_STATE: {
                defaultValue = currentState;
                inputUpdateFunc = setCurrentState;
                break;
            }
            case NAME_PROVINCE: {
                defaultValue = currentProvince;
                inputUpdateFunc = setCurrentProvince;
                break;
            }
            default: {
                defaultValue = userAndCompanyInfo[name];
            }
        }

        switch (type) {
            case TYPE_CHECKBOX: {
                return (
                    <div key={inputKey}>
                        <FormLabel
                            labelText={title}
                            required={isRequired}
                            labelProps={n('label').props}
                            textProps={n('text').props}
                        >
                            {item.options.map(option => (
                                <CheckboxUncontrolled
                                    key={option.value}
                                    name={name}
                                    value={option.value}
                                    label={option.label}
                                    required={isRequired}
                                    inputRef={register(validationRules)}
                                />
                            ))}
                        </FormLabel>
                        {errorMessage && (
                            <span {...n('error').props} aria-live="assertive">
                                {errorMessage}
                            </span>
                        )}
                    </div>
                );
            }
            case TYPE_TEXTAREA: {
                const maxLength = item.editorAttrs && item.editorAttrs.maxlength;

                return (
                    <Textarea
                        key={inputKey}
                        name={name}
                        label={title}
                        required={isRequired}
                        placeholder={placeholder}
                        maxLength={maxLength}
                        inputRef={register(validationRules)}
                        error={errorMessage}
                    />
                );
            }
            case TYPE_SELECT:
            case TYPE_STYLED_SELECT:
                return (
                    <Select
                        key={inputKey}
                        name={name}
                        label={title}
                        defaultValue={defaultValue}
                        required={isRequired}
                        placeholder={placeholder || i18nLeadsWithDefaults.select}
                        onChange={inputUpdateFunc}
                        options={optionList}
                        i18n={i18nLeadsWithDefaults}
                        hookFormControl={control}
                        validationRules={validationRules}
                        error={errorMessage}
                        isSearchable
                    />
                );
            default:
                return (
                    <Input
                        key={inputKey}
                        name={name}
                        label={title}
                        defaultValue={defaultValue}
                        type={type && type.toLowerCase()}
                        hint={hint}
                        i18n={i18nLeadsWithDefaults}
                        addon={addon}
                        addonLabel={addonLabel}
                        required={isRequired}
                        error={errorMessage}
                        inputRef={register(validationRules)}
                    />
                );
        }
    };

    const renderCustomFields = () => {
        if (!custom || !custom.length) {
            return null;
        }

        return custom.map(item => (
            <div {...n('formGroup').props} key={item.name}>
                {renderInput(item)}
            </div>
        ));
    };

    const renderButtons = (
        <div {...n('buttons').props}>
            <div {...n('submit').props}>
                <Button type="primary" action="submit" disabled={isPostingLead}>
                    {i18nLeadsWithDefaults.submit}
                </Button>
            </div>
        </div>
    );

    const renderStateProvinceBlock = () => {
        if (currentCountry && province && currentCountry.value_iso3 === province.visibleOn) {
            return renderInput(province);
        }

        if (currentCountry && state && currentCountry.value_iso3 === state.visibleOn) {
            return renderInput(state);
        }

        return null;
    };

    const renderPhoneBlock = () => (
        <div {...n('row').props}>
            {phone && <div {...n('col', isMobile ? '8' : '9').props}>{renderInput(phone)}</div>}
            {phoneExtension && <div {...n('col', isMobile ? '4' : '3').props}>{renderInput(phoneExtension)}</div>}
        </div>
    );

    return (
        <section {...n('container').props} ref={containerRef}>
            <GridContainer {...n('container').props}>
                <div {...n('content').props}>
                    {i18nLeadsWithDefaults.title && (
                        <div {...n('header').props}>
                            <h2 {...n('title').props}>{i18nLeadsWithDefaults.title}</h2>
                        </div>
                    )}
                    {i18nLeadsWithDefaults.instructions && (
                        <div
                            {...n('instructions').props}
                            dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(i18nLeadsWithDefaults.instructions) }}
                        />
                    )}
                    <form {...n('form').props} onSubmit={handleSubmit(onFormValid)} noValidate>
                        {errorStatus && (
                            <Alert
                                alertMessage={i18nLeadsWithDefaults.errorMessage}
                                type={alertTypes.ERROR_ALERT}
                                onClick={() => setErrorStatus(false)}
                                scrollIntoView
                                closeAlert={i18nLeadsWithDefaults.closeAlert}
                            />
                        )}
                        <Grid maxCol={columns} useUniqueGridItemClassname>
                            {firstName && renderInput(firstName)}
                            {lastName && renderInput(lastName)}
                            {email && renderInput(email)}
                            {(phone || phoneExtension) && renderPhoneBlock()}
                            {companyName && renderInput(companyName)}
                            {companySize && <Grid maxCol={columns} name="formCompanySize">{renderInput(companySize)}</Grid>}
                            {street1 && renderInput(street1)}
                            {street2 && renderInput(street2)}
                            {city && renderInput(city)}
                            <Grid maxCol={columns} name="formStateZip">
                                {renderStateProvinceBlock()}
                                {zip && renderInput(zip)}
                            </Grid>
                            {country && renderInput(country)}
                        </Grid>
                        {notes && <div {...n('formGroup formNotes').props}>{notes && renderInput(notes)}</div>}
                        {renderCustomFields()}
                        {renderButtons}
                    </form>
                    <div {...n('closeButton').props}>
                        <Button buttonType="icon" onClick={closeForm}>
                            <span {...n('closeButtonText').props}>{i18nLeadsWithDefaults.closeLeadForm}</span>
                            <span {...n('closeButtonIcon').props}>
                                <Icon type="close" width="24px" />
                            </span>
                        </Button>
                    </div>
                </div>
            </GridContainer>
            <Modal
                currentKey={showRecaptchaModal ? 'lead-recaptcha' : ''}
                left={recaptchaModalPosition.left}
                top={recaptchaModalPosition.top}
                showBackdrop={showRecaptchaModal}
                backdropBlur={showRecaptchaModal}
                onClose={closeRecaptchaModal}
                currentItem={showRecaptchaModal ? (
                    <div {...n('recaptchaModal').props}>
                        <h2 {...n('recaptchaModalTitle').props}>
                            {i18nLeadsWithDefaults.recaptchaModalTitle}
                        </h2>
                        <p {...n('recaptchaModalDescription').props}>
                            {i18nLeadsWithDefaults.recaptchaModalDescription}
                        </p>
                        <ReCAPTCHA
                            ref={recaptchaRef}
                            sitekey={recaptchaPublicKey}
                            onChange={handleRecaptchaChange}
                            onErrored={() => setRecaptchaError(true)}
                            onExpired={() => setRecaptchaToken(null)}
                        />
                        {recaptchaError && (
                            <Alert
                                alertMessage={i18nLeadsWithDefaults.recaptchaError}
                                type={alertTypes.ERROR_ALERT}
                                onClick={() => setRecaptchaError(false)}
                                closeAlert={i18nLeadsWithDefaults.closeAlert}
                            />
                        )}
                        <div {...n('recaptchaModalActions').props}>
                            <Button type="secondary" onClick={closeRecaptchaModal} disabled={isPostingLead}>
                                {i18nLeadsWithDefaults.recaptchaCancel}
                            </Button>
                            <Button
                                type="primary"
                                onClick={onRecaptchaModalSubmit}
                                disabled={isPostingLead || !recaptchaToken}
                            >
                                {i18nLeadsWithDefaults.recaptchaConfirm}
                            </Button>
                        </div>
                    </div>
                ) : null}
            />
        </section>
    );
};

LeadForm.propTypes = {
    data: PropTypes.shape(leadsPropTypes)
};

LeadForm.defaultProps = {
    data: {
        form: {
            actionEndpoint: '',
            schema: {}
        },
        i18n: {
            submit: 'Send',
            cancel: 'Close',
            defaultError: 'Please fill out the required fields.',
            select: 'Select',
            closeAlert: 'Close alert',
            closeLeadForm: 'Close lead form',
            instructions: '',
            fieldRequired: 'Required',
            phoneExtension: 'Phone Extension',
            countryCode: 'Country Code',
            maxLengthError: 'Please shorten your input by removing some text to fit within {maxLength} characters.',
            // Character counter strings
            charactersLeftFew: 'Only {remaining} character left',
            charactersLeftFewPlural: 'Only {remaining} characters left',
            charactersRemaining: '{remaining} character remaining',
            charactersRemainingPlural: '{remaining} characters remaining',
            characterLimitReached: 'Character limit reached',
            charactersOverLimit: '{remaining} character over limit',
            charactersOverLimitPlural: '{remaining} characters over limit',
            recaptchaModalTitle: 'Verify you are not a robot',
            recaptchaModalDescription: 'Please complete the verification below to submit your information.',
            recaptchaCancel: 'Cancel',
            recaptchaConfirm: 'Submit',
            recaptchaError: 'Verification failed. Please try again.'
        }
    }
};

LeadForm.schema = () => ({
    name: 'ProductLeadForm',
    title: 'uieditor.sfbComponent.leadForm.title',
    iconName: '',
    form: {},
    marketplaceData: {
        form: 'application.leads.form',
        i18n: 'application.leads.i18n',
        leadsRecaptchaEnabled: 'leadsRecaptchaEnabled',
        recaptchaKeys: 'recaptchaKeys',
        config: 'config'
    }
});

export default withListener(LeadForm);
