import React from 'react';
import PropTypes from 'prop-types';
import DOMPurify from 'dompurify';
import './styles/FeatureDetails.scss';
import { createNamespace } from '../../tools/namingTools';
import Image from '../../atoms/image/Image';
import Icon from '../../atoms/icon/Icon';
import { DROPDOWN, TOGGLE, COLORPICKER, RADIO } from '../../constants/schemaComponentTypes';
import { CENTER, LEFT, RIGHT, ALTERNATING } from '../../constants/alignment';
import { COL_ONE, COL_TWO } from '../../constants/columns';
import { FEATURE_BACKGROUND } from '../../constants/backgroundSettings';
import withListener from '../withListener';

const n = createNamespace('FeatureDetails');

export const BOX_SHADOW_DIMENSIONS = '0 5px 10px 5px';
const DEFAULT_BOX_SHADOW_COLOR = 'rgba(0, 0, 0, 0.1)';
const ALIGNMENT_OPTIONS = [LEFT, CENTER, RIGHT];
const IMAGE_POSITION_OPTIONS = [LEFT, RIGHT, ALTERNATING];
const COLUMN_COUNT = [COL_ONE, COL_TWO];

const SETTINGS = {
    columnCount: {
        title: 'uieditor.sfbComponent.featuredDetails.columnCount.title',
        type: DROPDOWN,
        defaultValue: COLUMN_COUNT[1].value,
        options: COLUMN_COUNT,
        validation: {
            availableOptions: COLUMN_COUNT,
            message: 'uieditor.sfbComponent.dropdown.validation.message',
            default: 'uieditor.sfbComponent.dropdown.defaultValue'
        }
    },
    alignment: {
        title: 'uieditor.sfbComponent.featuredDetails.alignment.title',
        type: RADIO,
        defaultValue: ALIGNMENT_OPTIONS[0].value,
        options: ALIGNMENT_OPTIONS,
        validation: {
            availableOptions: ALIGNMENT_OPTIONS.map(({ value }) => value),
            message: 'uieditor.sfbComponent.dropdown.validation.message'
        }
    },
    isHighlightsCheckEnabled: {
        labelOn: 'uieditor.sfbComponent.featuredDetails.isHighlightsCheckEnabled.labelOn',
        labelOff: 'uieditor.sfbComponent.featuredDetails.isHighlightsCheckEnabled.labelOff',
        defaultValue: false,
        type: TOGGLE
    },
    imagePosition: {
        title: 'uieditor.sfbComponent.featuredDetails.imagePosition.title',
        type: DROPDOWN,
        defaultValue: IMAGE_POSITION_OPTIONS[2].value,
        options: IMAGE_POSITION_OPTIONS,
        validation: {
            availableOptions: IMAGE_POSITION_OPTIONS.map(({ value }) => value),
            message: 'uieditor.sfbComponent.dropdown.validation.message',
            default: 'uieditor.sfbComponent.dropdown.defaultValue'
        }
    },
    enableImageShadow: {
        title: 'uieditor.sfbComponent.featuredDetails.enableImageShadow.title',
        type: TOGGLE,
        defaultValue: true,
        labelOn: 'uieditor.sfbComponent.featuredDetails.enableImageShadow.labelOn',
        labelOff: 'uieditor.sfbComponent.featuredDetails.enableImageShadow.labelOff'
    },
    imageShadowColor: {
        title: 'uieditor.sfbComponent.featuredDetails.imageShadowColor.title',
        type: COLORPICKER,
        defaultValue: DEFAULT_BOX_SHADOW_COLOR
    },
    backgroundBlockingColor: {
        title: 'uieditor.sfbComponent.featuredDetails.backgroundBlockingColor.title',
        type: COLORPICKER,
        defaultValue: FEATURE_BACKGROUND
    }
};

export const FeatureDetailsComponent = props => {
    // TODO: Remove these default assignments once
    // toolkit is fixed since an empty settings object is passed in
    const {
        settings,
        data: { items: features }
    } = props;

    const settingsWithDefaults = { ...FeatureDetailsComponent.defaultProps.settings, ...settings };

    const {
        alignment,
        isHighlightsCheckEnabled,
        imagePosition,
        imageShadowColor,
        enableImageShadow,
        columnCount,
        backgroundBlockingColor
    } = settingsWithDefaults;

    const cssVariables = {
        'text-align': alignment,
        'background-color': backgroundBlockingColor
    };

    const boxShadow = `${BOX_SHADOW_DIMENSIONS} ${imageShadowColor}`;
    const containerModifiers = [`image-${imagePosition}`, `align-${alignment}`];

    if (columnCount === COL_TWO.value) {
        containerModifiers.push('two-column');
    }

    const renderCharacteristics = characteristics => {
        if (!characteristics || !characteristics.length) {
            return null;
        }

        const modifiers = [isHighlightsCheckEnabled && 'with-icon'];

        return (
            <div {...n('characteristic').props}>
                {characteristics.map(characteristic => (
                    <div {...n('characteristicItem').props} key={characteristic.position}>
                        <h2 {...n('title').props}>{characteristic.title}</h2>
                        {characteristic.highlights.map(({ highlight }) => (
                            <span key={highlight} {...n('highlight_wrapper', modifiers).withTestId().props}>
                                {isHighlightsCheckEnabled && <Icon type="check" {...n('icon', 'check').withTestId().props} />}
                                <p
                                    key={highlight}
                                    dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(highlight) }}
                                    {...n('description').props}
                                />
                            </span>
                        ))}
                    </div>
                ))}
            </div>
        );
    };

    const renderFeature = feature => {
        const featureModifiers = [];
        const imageStyle = {};

        if (feature.imageUrl) {
            featureModifiers.push('with-image');
        }

        if (enableImageShadow) {
            imageStyle.boxShadow = boxShadow;
        }

        return (
            <section {...n('container').withTestId().withE2EId().props} key={feature.id}>
                <div {...n('content').props}>
                    <div {...n('row').props}>
                        <div {...n('feature', featureModifiers).props}>
                            <h1 {...n('title').withE2EId().props}>{feature.label}</h1>
                            <p {...n('description').withE2EId().props}>{feature.description}</p>
                            {renderCharacteristics(feature.aboveCharacteristics)}
                            {renderCharacteristics(feature.belowCharacteristics)}
                        </div>
                        {feature.imageUrl && (
                            <div {...n('imageContainer').withTestId().props}>
                                <Image
                                    {...n('image').withTestId().withE2EId().props}
                                    src={feature.imageUrl}
                                    style={imageStyle}
                                    alt={feature.label}
                                />
                            </div>
                        )}
                    </div>
                </div>
            </section>
        );
    };

    if (!features || !features.length) {
        return null;
    }

    return (
        <div {...n('wrapper', containerModifiers).withVariables(cssVariables).withTestId().props}>
            {features.map(renderFeature)}
        </div>
    );
};

FeatureDetailsComponent.schema = () => ({
    name: 'FeatureDetails',
    title: 'uieditor.sfbComponent.featuredDetails.title',
    iconName: 'special',
    form: SETTINGS,
    marketplaceData: {
        items: 'application.features.items'
    },
    requiredDataFunc: ({ items }) => (items && items.length)
});

FeatureDetailsComponent.propTypes = {
    settings: PropTypes.shape({
        alignment: PropTypes.oneOf([CENTER.value, LEFT.value, RIGHT.value]),
        isHighlightsCheckEnabled: PropTypes.bool,
        imageShadowColor: PropTypes.string,
        backgroundBlockingColor: PropTypes.string,
        columnCount: PropTypes.oneOf([COL_ONE.value, COL_TWO.value]),
        imagePosition: PropTypes.oneOf([LEFT.value, RIGHT.value, ALTERNATING.value]),
        enableImageShadow: PropTypes.bool
    }),
    data: PropTypes.shape({
        items: PropTypes.arrayOf(PropTypes.shape({
            id: PropTypes.number.isRequired,
            label: PropTypes.string.isRequired,
            description: PropTypes.string.isRequired,
            imageUrl: PropTypes.string,
            aboveCharacteristics: PropTypes.arrayOf(PropTypes.shape({
                id: PropTypes.number,
                title: PropTypes.string.isRequired,
                position: PropTypes.number.isRequired,
                belowPicture: PropTypes.bool.isRequired,
                highlights: PropTypes.arrayOf(PropTypes.shape({
                    highlight: PropTypes.string.isRequired,
                    displayCheck: PropTypes.bool.isRequired
                }))
            })),
            belowCharacteristics: PropTypes.arrayOf(PropTypes.shape({
                id: PropTypes.number,
                title: PropTypes.string.isRequired,
                position: PropTypes.number.isRequired,
                abovePicture: PropTypes.bool.isRequired,
                highlights: PropTypes.arrayOf(PropTypes.shape({
                    highlight: PropTypes.string.isRequired,
                    displayCheck: PropTypes.bool.isRequired
                }))
            }))
        }))
    })
};

FeatureDetailsComponent.defaultProps = {
    settings: {
        alignment: SETTINGS.alignment.defaultValue,
        isHighlightsCheckEnabled: SETTINGS.isHighlightsCheckEnabled.defaultValue,
        imagePosition: SETTINGS.imagePosition.defaultValue,
        enableImageShadow: SETTINGS.enableImageShadow.defaultValue,
        imageShadowColor: SETTINGS.imageShadowColor.defaultValue,
        backgroundBlockingColor: SETTINGS.backgroundBlockingColor.defaultValue,
        columnCount: SETTINGS.columnCount.defaultValue
    },
    data: {
        items: []
    }
};

export default withListener(FeatureDetailsComponent);
