import React from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { hasSupportInfo, hasSidebar, hasTags, hasCustomAttributes, hasContactInfo } from '../../tools/components/productAdditionalInfo';
import { productAdditionalInfoDataPropTypes, productAdditionalInfoSettingsPropTypes } from '../../constants/components/prop-types/product-additional-info';
import { DROPDOWN, COLORPICKER, GROUP_HEADER } from '../../constants/schemaComponentTypes';
import { COLUMN_COUNT_OPTIONS, INFO_POSITION_OPTIONS } from '../../constants/components/product-additional-info';
import { LEFT, RIGHT } from '../../constants/alignment';
import { NAMESPACES } from '../../constants/namespaces';
import withListener from '../withListener';
import SideBar from '../../atoms/side-bar/SideBar';
import './styles/AdditionalInfo.scss';

const n = createNamespace('additionalInfo');

const renderInfoLink = (title, url) => (
    <a {...n('link').withTestId().withE2EId().props} href={url}>{title || url}</a>
);

const AdditionalInfo = ({
    data: {
        support: info,
        relatedContent = {},
        customAttributes = []
    },
    settings
}) => {
    // Support Informations are required for this component
    if (!hasSupportInfo(info)) {
        return null;
    }

    const {
        i18n: i18nInfo = {}
    } = info;

    const settingsWithDefaults = { ...AdditionalInfo.defaultProps.settings, ...settings };
    const {
        columnCount,
        headerBackground,
        infoPosition,
        sideBarBackground,
        sideBarBorder
    } = settingsWithDefaults;

    const showSidebar = hasSidebar(relatedContent, customAttributes);
    const isSidebarLeft = infoPosition && infoPosition === RIGHT.value;

    const infoColumnModifier = columnCount && `col-${columnCount}`;
    const sidebarLeftModifier = isSidebarLeft && 'sidebar-left';

    const componentVariables = {
        'info-length': info.length,
        'info-column': columnCount,
        'sidebar-position': isSidebarLeft && 'left'
    };

    const gridModifiers = [
        infoColumnModifier,
        sidebarLeftModifier,
        hasSidebar && 'with-sidebar'
    ];

    const renderInfoBlock = () => {
        const {
            description,
            documentationUrl,
            knowledgebaseUrl,
            email,
            phone,
            termsUrl,
            privacyUrl
        } = info;

        const infoModifiers = [
            infoColumnModifier,
            sidebarLeftModifier
        ];

        return (
            <React.Fragment>
                {hasContactInfo(termsUrl, privacyUrl) && (
                    <div {...n('info', infoModifiers).withTestId().withE2EId().props}>
                        <h3 {...n('sectionHeader').props}>{i18nInfo.termsAndConditions}</h3>
                        {termsUrl && (
                            <div {...n('content').props}>
                                {renderInfoLink(i18nInfo.termsUrl, termsUrl)}
                            </div>
                        )}
                        {privacyUrl && (
                            <div {...n('content').props}>
                                {renderInfoLink(i18nInfo.privacyUrl, privacyUrl)}
                            </div>
                        )}
                    </div>
                )}
                {hasContactInfo(description, email, phone, knowledgebaseUrl, documentationUrl) && (
                    <div {...n('info', infoModifiers).withTestId().withE2EId().props}>
                        <h3 {...n('sectionHeader').props}>{i18nInfo.support}</h3>
                        {description && (
                            <p {...n('description').props}>{description}</p>
                        )}
                        {email && (
                            <div {...n('content').props}>
                                <span {...n('label').props}>{i18nInfo.email}</span>
                                <a {...n('link').props} href={`mailto:${email}`}>{email}</a>
                            </div>
                        )}
                        {phone && (
                            <div {...n('content', 'phone').props}>
                                <span {...n('label').props}>{i18nInfo.phone}</span>
                                {phone}
                            </div>
                        )}
                        {knowledgebaseUrl && (
                            <div {...n('content', 'knowledgebase').withTestId('knowledgebase').props}>
                                {renderInfoLink((i18nInfo.knowledgebaseUrl), knowledgebaseUrl)}
                            </div>
                        )}
                        {documentationUrl && (
                            <div {...n('content', 'documentation').withTestId('documentation').props}>
                                {renderInfoLink(i18nInfo.documentation, documentationUrl)}
                            </div>
                        )}
                    </div>
                )}
            </React.Fragment>
        );
    };

    const renderSidebarBlock = () => {
        const { details, i18n = {} } = relatedContent;

        const tagNav = hasTags(details) ? [{
            title: i18n.tags || AdditionalInfo.defaultProps.data.relatedContent.i18n.tags,
            items: details.tags
        }] : [];

        const customAttributeNav = hasCustomAttributes(customAttributes) ? [{
            title: i18n.details,
            items: customAttributes.map(item => (
                {
                    title: item.label,
                    items: [{
                        label: item.value
                    }]
                }
            ))
        }] : [];

        const props = {
            navItems: [
                ...tagNav,
                ...customAttributeNav
            ],
            headerBackground,
            sideBarBackground,
            sideBarBorder
        };

        return (
            <div {...n('sidebar', isSidebarLeft && 'left').withTestId().withE2EId().props}>
                <SideBar {...props} />
            </div>
        );
    };

    return (
        <div {...n('container').withVariables(componentVariables).withTestId().withE2EId().props}>
            {i18nInfo.title && (
                <div {...n('header').props}>
                    <h2 {...n('title').withE2EId().props}>{i18nInfo.title}</h2>
                </div>
            )}
            <div {...n('grid', gridModifiers).withTestId().withE2EId().props}>
                {info && renderInfoBlock()}
                {showSidebar && renderSidebarBlock()}
            </div>
        </div>
    );
};

AdditionalInfo.schema = () => ({
    name: 'ProductAdditionalInfo',
    title: 'uieditor.sfbComponent.additionalInfo.title',
    anchor: 'product-section-support',
    iconName: 'info',
    orderableSection: [NAMESPACES.profile],
    form: {
        columnCount: {
            title: 'uieditor.sfbComponent.additionalInfo.columnCount.title',
            type: DROPDOWN,
            defaultValue: '1',
            options: COLUMN_COUNT_OPTIONS
        },
        headingSpacer: {
            type: GROUP_HEADER,
            title: 'uieditor.sfbComponent.additionalInfo.sidebarSettings.title',
            symbol: 'style'
        },
        infoPosition: {
            title: 'uieditor.sfbComponent.additionalInfo.infoPosition.title',
            type: DROPDOWN,
            defaultValue: LEFT.value,
            options: INFO_POSITION_OPTIONS
        },
        headerBackground: {
            title: 'uieditor.sfbComponent.additionalInfo.headerBackground.title',
            defaultValue: '#F5F5F5',
            type: COLORPICKER
        },
        sideBarBackground: {
            title: 'uieditor.sfbComponent.additionalInfo.sideBar.title',
            defaultValue: '#FFFF',
            type: COLORPICKER
        },
        sideBarBorder: {
            title: 'uieditor.sfbComponent.additionalInfo.sideBarBorder.title',
            defaultValue: '#CBCBCB',
            type: COLORPICKER
        }
    },
    requiredDataFunc: ({ support }) => hasSupportInfo(support),
    marketplaceData: {
        support: 'application.support',
        relatedContent: 'application.relatedContent',
        customAttributes: 'application.customAttributes'
    }
});

const SETTINGS = AdditionalInfo.schema().form;

AdditionalInfo.propTypes = {
    data: PropTypes.shape(productAdditionalInfoDataPropTypes),
    settings: PropTypes.shape(productAdditionalInfoSettingsPropTypes)
};

AdditionalInfo.defaultProps = {
    data: {
        support: {},
        relatedContent: {
            i18n: {
                tags: 'Categories'
            }
        },
        customAttributes: []
    },
    settings: {
        columnCount: SETTINGS.columnCount.defaultValue,
        infoPosition: SETTINGS.infoPosition.defaultValue,
        headerBackground: SETTINGS.headerBackground.defaultValue,
        sideBarBackground: SETTINGS.sideBarBackground.defaultValue,
        sideBarBorder: SETTINGS.sideBarBorder.defaultValue
    }
};

export default withListener(AdditionalInfo);
