import { TYPE_CHECKBOX } from '../../constants/components/lead-form';

/**
 * Parse custom attribute checkbox values
 * If array, removes values that are not part of the options
 *      e.g. checkboxOptions = ["A", "B"]
 *           ["A", null, "B", false] -> ["A", "B"]
 * If string/boolean value and part of options, make an array
 *      e.g. "A" -> ["A"]
 * If not in options, or all other cases
 *      e.g. false  -> []
 *
 * @param {Array|String|Boolean} value the checkbox value
 * @param {Array} checkboxOptions the options defined in the checkbox schema
 * @returns {Array} checkbox values that satisfy the Leads API contract
 */
export const parseCustomCheckboxes = (value, checkboxOptions = []) => {
    if (Array.isArray(value)) {
        return value.filter(val => checkboxOptions?.includes(val));
    }
    if (checkboxOptions?.includes(value)) {
        return [value];
    }
    return [];
};

/**
 * get all the checkbox inputs and its options
 *
 * @param {Array} customAttributesSchemas
 *  e.g [
            { name: 'yes_or_no', type: 'Checkboxes', options: [ { value: 'YES' } ]},
            { name: 'multi_select', type: 'Checkboxes', options: [ { value: 'A' }, { value: 'B' } ]},
            { name: 'notes', type: 'Text'}
        ]
 * @returns {Object} custom checkboxes with key=checkbox_name, value=options array
    e.g.  {
        yes_or_no: ['YES']
        multi_select: ['A', 'B']
    }
 */
export const getCustomCheckboxes = (customAttributesSchemas = []) => customAttributesSchemas.reduce(
    (accumulator, input) => {
        if (input?.type === TYPE_CHECKBOX && input?.name) {
            accumulator[input.name] = input?.options?.map(option => option?.value);
        }
        return accumulator;
    }, {}
);

export const parseCustomAttr = (attrs = {}, customAttributesSchemas) => {
    const customAttributes = {};
    const customCheckboxes = getCustomCheckboxes(customAttributesSchemas);

    Object.keys(attrs).forEach(key => {
        const value = attrs[key];

        if (customCheckboxes[key]) {
            customAttributes[key] = parseCustomCheckboxes(value, customCheckboxes[key]);
        } else if (Array.isArray(value)) {
            customAttributes[key] = value;
        } else {
            customAttributes[key] = [value];
        }
    });
    return customAttributes;
};

export const getDefaultSelectedOption = schema => {
    if (!schema || !schema.options || !schema.options.length) {
        return '';
    }

    return schema.options.find(item => item.isSelected);
};

export const createPostPayload = (otherData, formData, customAttributesSchemas) => {
    const {
        companyName,
        companySize,
        street1,
        street2,
        city,
        state,
        province,
        zip,
        country,
        firstName,
        lastName,
        email,
        phone,
        phoneExtension,
        notes,
        comment,
        ...customAttributes
    } = formData;
    const customAttrs = parseCustomAttr(customAttributes, customAttributesSchemas);
    const payload = {
        ...otherData,
        customer: {
            company: {
                name: companyName,
                size: companySize && companySize.value,
                street1,
                street2,
                city,
                state: state ? state.value : province && province.value,
                zip,
                country: country && country.value
            },
            contact: {
                firstName,
                lastName,
                email,
                phone,
                phoneExtension: phoneExtension || ''
            }
        },
        customAttributes: customAttrs,
        notes,
        comment
    };
    return payload;
};

export const sanitizePhoneData = (formData = {}, currentCountryCode) => {
    if (!formData.phone) {
        return '';
    }

    if (formData.phone && formData.phone.trim() === currentCountryCode) {
        return '';
    }

    return formData.phone;
};
