import React from 'react';
import PropTypes from 'prop-types';
import DOMPurify from 'dompurify';
import { createNamespace } from '../../tools/namingTools';
import { SMALL, MEDIUM } from '../../constants/sizes';
import Image from '../image/Image';
import { getImageSrc } from '../../tools/images';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/FeatureCard.scss';

const n = createNamespace('FeatureCard');

const FeatureCard = ({
    title,
    description,
    image,
    imageSize,
    withHeading,
    ...otherProps
}) => {
    const {
        className: extraClass
    } = otherProps;

    const renderImage = () => {
        const { alt, url, urlSrcset } = image;

        return (
            <Image
                {...n('image', imageSize).props}
                src={getImageSrc(url, urlSrcset)}
                alt={alt}
            />
        );
    };

    return (
        <article {...n('wrapper').withClass(extraClass).props}>
            {image && renderImage()}
            <div {...n('content').props}>
                {title && (
                    <h2 {...n('title', withHeading && 'heading').withTestId().withE2EId().props}>
                        {title}
                    </h2>
                )}
                {description && (
                    <div {...n('description').withTestId().withE2EId().props} dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(description) }} />
                )}
            </div>
        </article>
    );
};

const featureCardImageShape = {
    alt: PropTypes.string,
    url: PropTypes.string,
    urlSrcset: PropTypes.shape({
        default: PropTypes.string,
        '1x': PropTypes.string,
        '2x': PropTypes.string
    })
};

FeatureCard.propTypes = {
    title: PropTypes.string,
    description: PropTypes.string,
    image: PropTypes.shape(featureCardImageShape),
    imageSize: PropTypes.oneOf([SMALL.value, MEDIUM.value]),
    withHeading: PropTypes.bool
};

FeatureCard.defaultProps = {
    title: '',
    description: '',
    image: null,
    imageSize: null,
    withHeading: false
};

export default FeatureCard;
