import React from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { navigateTo } from '../../tools/urlTools';
import { replacePlaceholders } from '../../tools/stringTools';
import { TAG_TYPE_CATEGORY } from '../../constants/tags';
import { productQuickviewDataPropTypes } from '../../constants/components/prop-types/product-quickview';
import { productQuickviewSettingsPropTypes, productQuickviewSchemaForm, LAYOUT_DETAILED, LAYOUT_2COLUMNS, LAYOUT_DEFAULT } from '../../constants/components/schemas/product-quickview';
import { generateUniqueID } from '../../tools/helpers';
import Rating from '../rating/Rating';
import Pricing from '../pricing/Pricing';
import Image from '../image/Image';
import Button from '../button/Button';
import Icon from '../icon/Icon';
import './styles/ProductQuickView.scss';

const n = createNamespace('ProductQuickView');

const ProductQuickView = ({
    data: {
        name,
        blurb,
        iconSrcset,
        iconUrl,
        rating,
        ratingCaption,
        numRatings,
        overview,
        overviewImageUrl,
        description,
        startingPrice,
        tags,
        features,
        url,
        i18n
    },
    settings
}) => {
    // make sure we deep-merge default props
    const i18nWithDefaults = { ...ProductQuickView.defaultProps.data.i18n, ...i18n };
    const settingsWithDefaults = { ...ProductQuickView.defaultProps.settings, ...settings };

    const { quickviewViewMode } = settingsWithDefaults;
    const isScreenshotVisible = quickviewViewMode === LAYOUT_DEFAULT || quickviewViewMode === LAYOUT_2COLUMNS;

    const isDetailedViewMode = quickviewViewMode && quickviewViewMode === LAYOUT_DETAILED;

    // Variables used in the SCSS file, to keep all styles in css
    const componentVariables = {};

    const wrapperModifiers = [];

    if (quickviewViewMode) {
        wrapperModifiers.push(quickviewViewMode);
    }

    let screenshotBlock;
    if (isScreenshotVisible && overviewImageUrl) {
        const screenshotModifiers = 'align-left';
        screenshotBlock = (
            <div {...n('screenshot', screenshotModifiers).withTestId().props}>
                <Image
                    src={overviewImageUrl}
                    className={n('screenshotImage').props.className}
                    alt={overview}
                />
            </div>
        );
    }

    let ratingBlock = null;
    if (rating && numRatings) {
        ratingBlock = (
            <div {...n('rating').withTestId().props}>
                <Rating rating={rating} numRatings={numRatings} title={ratingCaption} displayRatingNumber={false} />
            </div>
        );
    }

    const mainLogoBlock = (
        <div {...n('imageWrapper').props}>
            <Image
                {...n('image').props}
                src={iconUrl}
                srcSet={iconSrcset}
                alt={blurb}
            />
        </div>
    );

    const summaryBlock = (
        <div {...n('summary').props}>
            <span {...n('title').props}>{name}</span>
            <p {...n('details').props}>{blurb}</p>
        </div>
    );

    const pricingBlock = startingPrice && (
        <div {...n('pricing').props}>
            <Pricing
                isEmphasis={false}
                isMultipleLine={false}
                caption={startingPrice.priceCaption}
                price={startingPrice.price}
                symbol={startingPrice.symbol}
                frequency={startingPrice.frequency.shortLabel}
            />
        </div>
    );

    const featureBlock = features && features.items && features.items.length && (
        <div {...n('feature').withTestId().props}>
            <span {...n('featureTitle').props}>{i18nWithDefaults.featuresTitle}</span>
            <ul {...n('featureList').props}>
                {features.items.map(item => (
                    <li key={generateUniqueID([item])} {...n('featureItem').props}>{item}</li>
                ))}
            </ul>
        </div>
    );

    // list of categories are in tags, as children of the CATEGORY tag
    const mainCategories = tags && tags.filter(tag => tag.type === TAG_TYPE_CATEGORY);
    const categories = mainCategories && mainCategories.reduce((carry, mainCategory) => {
        if (!mainCategory.children) {
            return carry;
        }
        return [
            ...carry,
            ...mainCategory.children
        ];
    }, []);

    const categoryBlock = categories && categories.length && (
        <div {...n('category').withTestId().props}>
            <span {...n('categoryTitle').props}>{i18nWithDefaults.categoriesTitle}</span>
            <ul {...n('categoryList').props} aria-label={i18nWithDefaults.categoriesTitle}>
                {categories.map(({ id, name: categoryName }) => (
                    <li key={generateUniqueID([id, categoryName])} {...n('categoryItem').props}>{categoryName}</li>
                ))}
            </ul>
        </div>
    );

    const descriptionBlock = description && (
        <p {...n('description').props}>{description}</p>
    );

    let buttonLabel = i18nWithDefaults.viewDetails;
    if (isDetailedViewMode) {
        buttonLabel = (
            <React.Fragment>
                {i18nWithDefaults.more}
                <Icon type="caretRight" fill="#fff" />
            </React.Fragment>
        );
    }

    const buttonBlock = (
        <div {...n('button').props}>
            <Button
                type="primary"
                size="small"
                onClick={() => { navigateTo(url); }}
                aria-label={replacePlaceholders(i18nWithDefaults.viewProductPage, { productName: name })}
            >
                {buttonLabel}
            </Button>
        </div>
    );

    const headerBlock = (
        <div {...n('header').props}>
            {isDetailedViewMode ? (
                <React.Fragment>
                    <div {...n('headerContent').props}>
                        {summaryBlock}
                        {ratingBlock}
                    </div>
                    {mainLogoBlock}
                </React.Fragment>
            ) : summaryBlock}
        </div>
    );

    const renderLayout = () => {
        switch (quickviewViewMode) {
            case LAYOUT_DETAILED:
                return (
                    <React.Fragment>
                        {headerBlock}
                        {pricingBlock}
                        {featureBlock}
                        {categoryBlock}
                        {descriptionBlock}
                        {buttonBlock}
                    </React.Fragment>
                );
            case LAYOUT_2COLUMNS:
                return (
                    <React.Fragment>
                        <div {...n('content').props}>
                            {headerBlock}
                            {pricingBlock}
                            {ratingBlock}
                            {descriptionBlock}
                            {buttonBlock}
                        </div>
                        {screenshotBlock}
                    </React.Fragment>
                );
            default:
                return (
                    <React.Fragment>
                        {headerBlock}
                        {pricingBlock}
                        {ratingBlock}
                        {descriptionBlock}
                        {screenshotBlock}
                        {buttonBlock}
                    </React.Fragment>
                );
        }
    };

    return (
        <div {...n('wrapper', wrapperModifiers).withTestId().withVariables(componentVariables).props}>
            {renderLayout()}
        </div>
    );
};

ProductQuickView.schema = () => ({
    name: 'Product Quickview',
    form: productQuickviewSchemaForm
});

ProductQuickView.propTypes = {
    data: PropTypes.shape(productQuickviewDataPropTypes),
    settings: PropTypes.shape(productQuickviewSettingsPropTypes)
};

const SETTINGS = ProductQuickView.schema();

ProductQuickView.defaultProps = {
    data: {
        i18n: {
            viewDetails: 'View Details',
            more: 'More',
            featuresTitle: 'Features',
            categoriesTitle: 'Categories',
            close: 'Close'
        }
    },
    settings: {
        quickviewViewMode: SETTINGS.form.quickviewViewMode.defaultValue
    }
};

export default ProductQuickView;
