import React from 'react';
import PropTypes from 'prop-types';
import DOMPurify from 'dompurify';
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 { ratingsSummaryDefaults } from '../../constants/default-props/ratings';
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 { getImageSrc } from '../../tools/images';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/ProductQuickView.scss';

const n = createNamespace('ProductQuickView');

const ProductQuickView = ({
    data: {
        name,
        blurb,
        iconSrcset,
        iconUrl,
        rating,
        numRatings,
        overview,
        overviewImageUrl,
        description,
        startingPrice,
        tags,
        features,
        url,
        i18n,
        ratingsSummary: {
            caption: ratingCaption,
            title: ratingTitle
        } = ratingsSummaryDefaults
    },
    settings,
    titleId
}) => {
    // 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={ratingTitle}
                    caption={ratingCaption}
                    displayRatingNumber={false}
                />
            </div>
        );
    }

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

    const summaryBlock = (
        <div {...n('summary').props}>
            <span {...n('title').props} {...(titleId && { id: titleId })}>{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}
                isConsistentDisplay={!!startingPrice.consistentPriceDisplayV2Enabled}
            />
        </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 && (
        <div {...n('description').props} dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(description) }} />
    );

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

    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 ? (
                <>
                    <div {...n('headerContent').props}>
                        {summaryBlock}
                        {ratingBlock}
                    </div>
                    {mainLogoBlock}
                </>
            ) : summaryBlock}
        </div>
    );

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

    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),
    titleId: PropTypes.string
};

const SETTINGS = ProductQuickView.schema();

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

export default ProductQuickView;
