import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import DOMPurify from 'dompurify';
import { createNamespace } from '../../tools/namingTools';
import { lowerFirst } from '../../tools/stringTools';
import { parseToBool } from '../../tools/helpers';
import { darken } from '../../tools/colorHelper';
import { useResponsive } from '../../tools/widths/useResponsive';
import { PRODUCT_DEFAULT_IMG } from '../../constants/images';
import { SLIDER, COLORPICKER, TOGGLE, DROPDOWN, RADIO } from '../../constants/schemaComponentTypes';
import { SMALL, MEDIUM, LARGE } from '../../constants/sizes';
import { GRID_VIEW, GRID_VIEW_TYPE, LIST_VIEW, LIST_VIEW_TYPE } from '../../constants/views';
import { itemsPropTypes as productListingCardShape } from '../../constants/prop-types/listingProducts/items';
import { i18nPropTypes } from '../../constants/prop-types/listingProducts/i18n';
import { ratingsSummaryDefaults } from '../../constants/default-props/ratings';
import Badge from '../badge/Badge';
import Checkbox from '../checkbox/Checkbox';
import Pricing from '../pricing/Pricing';
import Rating from '../rating/Rating';
import Image from '../image/Image';
import { ListingLoader, GridLoader } from '../../tools/LoaderSchema';
import { PRODUCT_LISTING_CARD_MAX_MERCHANDISING_BADGES } from '../../constants/components/product-listing-card';
import { renderBadge } from '../../tools/rendering/merchandisingBadges';
import { isContentFromOneWorldSync } from '../../tools/contentTools';
import { getImageSrc } from '../../tools/images';
import { getV2PricingSymbolProps } from '../../tools/components/pricing';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/ProductListingCard.scss';

const n = createNamespace('ProductListingCard');

const ProductListingCard = ({
    data: {
        id,
        name,
        blurb,
        overview,
        vendorName,
        url,
        hidePricings,
        iconUrl,
        iconSrcset = {},
        iconAlt,
        version,
        badges: initialBadges = [],
        rating,
        numRatings,
        startingPrice,
        productRibbon,
        free,
        merchandisingBadges,
        referUrl,
        ratingsSummary: {
            caption: ratingCaption,
            title: ratingTitle
        } = ratingsSummaryDefaults,
        useCheckoutForSpecialPricingMessage
    },
    showAsGrid,
    onCheckCompare,
    isCompareChecked,
    isDisabled,
    isLoading,
    i18n: i18nProp,
    i18nRating,
    locale,
    settings
}) => {
    const [badges, setBadges] = useState(initialBadges);
    useEffect(() => {
        if (useCheckoutForSpecialPricingMessage) {
            setBadges([...badges, {
                id: 'useCheckoutForSpecialPricingMessage',
                label: i18nProp?.useCheckoutForSpecialPricingMessageListing,
                type: 'success'
            }]);
        }
    }, []);

    const i18n = { ...ProductListingCard.defaultProps.i18n, ...i18nProp };

    const {
        iconSize,
        iconSizeGrid,
        borderRadius,
        titleColor,
        headerBackgroundColor,
        backgroundColor,
        borderColor,
        hoverColor,
        isCompareVisible,
        isRatingsVisible,
        isVendorVisible,
        isBlurbVisible,
        isOverviewVisible
    } = { ...ProductListingCard.defaultProps.settings, ...settings };

    const { mediumDown } = useResponsive();
    const isMobile = mediumDown;
    const viewMode = showAsGrid ? GRID_VIEW : LIST_VIEW;
    const containerModifiers = [viewMode];
    const imageContainerModifiers = [showAsGrid ? lowerFirst(iconSizeGrid) : lowerFirst(iconSize)];

    const [showRatings] = parseToBool(isRatingsVisible);
    const [showCompareBtn] = parseToBool(isCompareVisible);

    const shouldRenderRating = !!(showRatings && !!rating && numRatings > 0);

    // Variables used in the SCSS file, to keep all styles in css
    const componentVariables = { ...backgroundColor && {
        'card-container-bg-color': backgroundColor
    },
    ...headerBackgroundColor && showAsGrid && {
        'card-header-bg-color': headerBackgroundColor,
        'card-header-bg-color-hover': darken(headerBackgroundColor, 0.05)
    },
    ...titleColor && {
        'card-title-color': titleColor
    },
    ...borderColor && {
        'card-border-color': borderColor
    },
    ...borderRadius && {
        'card-border-radius': `${borderRadius}px`
    },
    ...hoverColor && {
        'card-container-bg-color-hover': hoverColor
    },
    ...productRibbon && {
        'card-ribbon-color': productRibbon.textColor,
        'card-ribbon-bg-color': productRibbon.ribbonColor
    } };

    const getLoader = () => {
        if (showAsGrid) {
            return <GridLoader />;
        }
        return <ListingLoader />;
    };

    // Render Blocks
    const imageBlock = (
        <Image
            src={getImageSrc(iconUrl, iconSrcset) || ProductListingCard.defaultProps.data.iconUrl}
            alt={iconAlt || name || 'Product image'}
            className={n('icon').props.className}
            isCopyRighted={isContentFromOneWorldSync(referUrl)}
        />
    );

    const versionBlock = version && (
        <span {...n('version').withTestId().props}>{`${i18n.version} ${version}`}</span>
    );

    const vendorNameBlock = isVendorVisible && vendorName && (
        <span {...n('vendor').withTestId().props}>{`${i18n.soldBy} ${vendorName}`}</span>
    );

    const merchandisingBadgesDisplay = merchandisingBadges && merchandisingBadges.length ? (
        <ul {...n('productBadges').withTestId().props} aria-label={i18n.merchandisingBadges}>
            {merchandisingBadges.slice(0, PRODUCT_LISTING_CARD_MAX_MERCHANDISING_BADGES).map(badge => (
                <li {...n('productBadgesItem').props} key={badge.uuid}>
                    {renderBadge(badge)}
                </li>
            ))}
        </ul>
    ) : '';

    const promoBadges = (
        <ul {...n('promoBadges', !showAsGrid && 'list').props} aria-label={i18n.badges}>
            {badges.map((badge, index) => {
                const badgeId = badge.id ? `${id}-${badge.id}-${index}` : `${id}-${index}`;
                const badgeProps = { ...badge, ...{ id: badgeId } };

                return (
                    <li {...n('badgeWrapper').props} key={badgeId}>
                        <Badge {...n('promoBadge').withTestId().props} {...badgeProps} />
                    </li>
                );
            })}
        </ul>
    );

    const blurbBlock = isBlurbVisible && (
        <div {...n('caption').withTestId().props}>{blurb}</div>
    );

    const overviewBlock = isOverviewVisible && (
        <div {...n('overview').withTestId().props} dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(overview) }} />
    );

    const badgeBlock = (badges?.length || merchandisingBadges?.length) ? (
        <div {...n('badges').withTestId().props}>
            {merchandisingBadgesDisplay}
            {promoBadges}
        </div>
    ) : '';

    const badgeBlockGrid = badges && badges.length ? (
        <div {...n('badges').withTestId().props}>
            {promoBadges}
        </div>
    ) : '';

    const ribbonBlock = productRibbon && (
        <div {...n('ribbon').withTestId().props}>
            {productRibbon.text}
        </div>
    );

    const tagsBlock = (ribbonBlock || badgeBlock) && (
        <div {...n('tags').withTestId().props}>
            {ribbonBlock}
            {badgeBlockGrid}
        </div>
    );

    const ratingBlock = shouldRenderRating && (
        <div {...n('starsWrapper').withTestId().props}>
            <Rating
                rating={rating}
                numRatings={numRatings}
                caption={ratingCaption}
                title={ratingTitle}
                i18nRating={i18nRating}
                displayRatingNumber
            />
        </div>
    );

    const pricingCaption = !free ? i18n.from : null;
    const pricingFrequency = startingPrice && startingPrice.frequency && startingPrice.frequency.shortLabel
        ? startingPrice.frequency.label : null;
    const v2PricingProps = getV2PricingSymbolProps(startingPrice, locale);
    const pricingBlock = startingPrice && (
        <div {...n('pricing').withTestId().props}>
            <Pricing
                isEmphasis={!isMobile && !showAsGrid}
                isMultipleLine={!showAsGrid && !isMobile}
                caption={pricingCaption}
                price={startingPrice.price}
                align={isMobile || showAsGrid ? null : 'right'}
                symbol={startingPrice.symbol}
                frequency={pricingFrequency}
                {...v2PricingProps}
                maxPriceWidth="150"
                alignPriceRight
                verticallyAlignPriceAndFrequency={!showAsGrid}
            />
        </div>
    );

    const compareBlock = showCompareBtn && (
        <div {...n('compare', isDisabled && 'disabled').withTestId().props}>
            <Checkbox
                ariaLabel={`${i18n.selectToCompare}: ${name}`}
                label={i18n.compare}
                name={`compare-product-${id}`}
                isChecked={isCompareChecked}
                onChange={() => onCheckCompare && onCheckCompare(id)}
            />
        </div>
    );

    return (
        <article {...n('wrapper').withTestId().withE2EId().withVariables(componentVariables).props}>
            <a aria-label={name} href={url} {...n('overlayLink').props}>
                <span {...n('overlayLinkText').props}>{name}</span>
            </a>
            <div {...n('container', containerModifiers).withTestId().withE2EId().props}>
                {isLoading
                    ? getLoader()
                    : (
                        <>
                            <div {...n('header', headerBackgroundColor && 'with-bg-color').props}>
                                <div {...n('imageContainer', imageContainerModifiers).withTestId().props}>
                                    {imageBlock}
                                </div>
                                {showAsGrid && tagsBlock}
                                {!showAsGrid && ribbonBlock}
                            </div>
                            <div {...n('content').withTestId().props}>
                                <div {...n('information').props}>
                                    <div {...n('description').props}>
                                        <h2 {...n('title').withTestId().withE2EId('').props}>{name}</h2>
                                        {!showAsGrid && blurbBlock}
                                        {overviewBlock}
                                        {!showAsGrid && !isMobile && badgeBlock}
                                    </div>
                                    {(isMobile || showAsGrid) && merchandisingBadgesDisplay}
                                    {!hidePricings && pricingBlock}
                                </div>
                                <div {...n('footer').props}>
                                    {ratingBlock}
                                    {!showAsGrid && (
                                        <div {...n('footerCredit').props}>
                                            {versionBlock}
                                            {vendorNameBlock}
                                        </div>
                                    )}
                                    {compareBlock}
                                </div>
                            </div>
                        </>
                    )}
            </div>
        </article>
    );
};

const ICON_SIZE_OPTIONS = [SMALL, MEDIUM];
const ICON_SIZE__GRID_OPTIONS = [SMALL, MEDIUM, LARGE];
export const VIEW_TYPES = [LIST_VIEW_TYPE, GRID_VIEW_TYPE];

export const productListingCardForm = {
    defaultView: {
        title: 'uieditor.sfbComponent.productListCardForm.defaultView.title',
        type: RADIO,
        required: false,
        defaultValue: VIEW_TYPES[0].value,
        options: VIEW_TYPES
    },
    iconSize: {
        title: 'uieditor.sfbComponent.productListCardForm.iconSize.title',
        type: DROPDOWN,
        required: true,
        defaultValue: ICON_SIZE_OPTIONS[0].value,
        options: ICON_SIZE_OPTIONS
    },
    iconSizeGrid: {
        title: 'uieditor.sfbComponent.productListCardForm.iconSizeGrid.title',
        type: DROPDOWN,
        required: true,
        defaultValue: ICON_SIZE__GRID_OPTIONS[0].value,
        options: ICON_SIZE__GRID_OPTIONS
    },
    titleColor: {
        title: 'uieditor.sfbComponent.productListCardForm.titleColor.title',
        type: COLORPICKER,
        defaultValue: '#474747'
    },
    headerBackgroundColor: {
        title: 'uieditor.sfbComponent.productListCardForm.headerBackgroundColor.title',
        type: COLORPICKER,
        defaultValue: '#ffffff'
    },
    backgroundColor: {
        title: 'uieditor.sfbComponent.productListCardForm.backgroundColor.title',
        type: COLORPICKER,
        defaultValue: '#ffffff'
    },
    borderColor: {
        title: 'uieditor.sfbComponent.productListCardForm.borderColor.title',
        type: COLORPICKER,
        defaultValue: '#eaeaea'
    },
    hoverColor: {
        title: 'uieditor.sfbComponent.productListCardForm.hoverColor.title',
        type: COLORPICKER,
        defaultValue: 'rgba(0,0,0,0.05)'
    },
    borderRadius: {
        title: 'uieditor.sfbComponent.productListCardForm.borderRadius.title',
        type: SLIDER,
        defaultValue: 8,
        options: {
            range: true,
            min: 0,
            max: 35,
            step: 1
        }
    },
    isCompareVisible: {
        labelOn: 'uieditor.sfbComponent.productListCardForm.isCompareVisible.labelOn',
        labelOff: 'uieditor.sfbComponent.productListCardForm.isCompareVisible.labelOff',
        defaultValue: true,
        type: TOGGLE
    },
    isRatingsVisible: {
        labelOn: 'uieditor.sfbComponent.productListCardForm.isRatingsVisible.labelOn',
        labelOff: 'uieditor.sfbComponent.productListCardForm.isRatingsVisible.labelOff',
        defaultValue: true,
        type: TOGGLE
    },
    isVendorVisible: {
        labelOn: 'uieditor.sfbComponent.productListCardForm.isVendorVisible.labelOn',
        labelOff: 'uieditor.sfbComponent.productListCardForm.isVendorVisible.labelOff',
        defaultValue: true,
        type: TOGGLE
    },
    isBlurbVisible: {
        labelOn: 'uieditor.sfbComponent.productListCardForm.isBlurbVisible.labelOn',
        labelOff: 'uieditor.sfbComponent.productListCardForm.isBlurbVisible.labelOff',
        defaultValue: true,
        type: TOGGLE
    },
    isOverviewVisible: {
        labelOn: 'uieditor.sfbComponent.productListCardForm.isOverviewVisible.labelOn',
        labelOff: 'uieditor.sfbComponent.productListCardForm.isOverviewVisible.labelOff',
        defaultValue: true,
        type: TOGGLE
    }
};

ProductListingCard.schema = () => ({
    name: 'Product Listing Card',
    form: productListingCardForm
});

export const productListingSettingsShape = {
    iconSize: PropTypes.oneOf(ICON_SIZE_OPTIONS.map(({ value }) => value)),
    iconSizeGrid: PropTypes.oneOf(ICON_SIZE__GRID_OPTIONS.map(({ value }) => value)),
    borderRadius: PropTypes.number,
    titleColor: PropTypes.string,
    headerBackgroundColor: PropTypes.string,
    backgroundColor: PropTypes.string,
    borderColor: PropTypes.string,
    hoverColor: PropTypes.string,
    isCompareVisible: PropTypes.bool,
    isRatingsVisible: PropTypes.bool,
    isVendorVisible: PropTypes.bool,
    isBlurbVisible: PropTypes.bool,
    isOverviewVisible: PropTypes.bool
};

ProductListingCard.propTypes = {
    data: PropTypes.shape(productListingCardShape),
    i18n: PropTypes.shape(i18nPropTypes),
    i18nRating: PropTypes.shape({
        label: PropTypes.string
    }),
    locale: PropTypes.shape({
        code: PropTypes.string
    }),
    showAsGrid: PropTypes.bool,
    isCompareChecked: PropTypes.bool,
    isDisabled: PropTypes.bool,
    isLoading: PropTypes.bool,
    onCheckCompare: PropTypes.func,
    settings: PropTypes.shape(productListingSettingsShape)
};

const SETTINGS = ProductListingCard.schema().form;

ProductListingCard.defaultProps = {
    data: {
        hidePricings: false,
        iconUrl: PRODUCT_DEFAULT_IMG,
        ratingsSummary: ratingsSummaryDefaults,
        useCheckoutForSpecialPricingMessage: false
    },
    i18n: {
        version: 'Version',
        soldBy: 'Sold by',
        compare: 'Compare',
        rating: 'Rating',
        selectToCompare: 'Select to compare',
        from: 'From',
        badges: 'Badges',
        merchandisingBadges: 'Merchandising Badges'
    },
    i18nRating: null,
    locale: null,
    showAsGrid: false,
    isCompareChecked: false,
    isDisabled: false,
    isLoading: false,
    onCheckCompare: null,
    settings: {
        iconSize: SETTINGS.iconSize.defaultValue,
        iconSizeGrid: SETTINGS.iconSizeGrid.defaultValue,
        borderRadius: SETTINGS.borderRadius.defaultValue,
        titleColor: SETTINGS.titleColor.defaultValue,
        headerBackgroundColor: SETTINGS.headerBackgroundColor.defaultValue,
        backgroundColor: SETTINGS.backgroundColor.defaultValue,
        borderColor: SETTINGS.borderColor.defaultValue,
        hoverColor: SETTINGS.hoverColor.defaultValue,
        isCompareVisible: SETTINGS.isCompareVisible.defaultValue,
        isRatingsVisible: SETTINGS.isRatingsVisible.defaultValue,
        isVendorVisible: SETTINGS.isRatingsVisible.defaultValue,
        isBlurbVisible: SETTINGS.isBlurbVisible.defaultValue,
        isOverviewVisible: SETTINGS.isOverviewVisible.defaultValue
    }
};

export default ProductListingCard;
