import React from 'react';
import DOMPurify from 'dompurify';
import './styles/CollapsibleText.scss';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import Icon from '../icon/Icon';

const n = createNamespace('CollapsibleText');
const Collapsible = ({
    faqData,
    listPadding,
    isSelected,
    isExpandable,
    selectedBackgroundColor,
    onSetIndex,
    index
}) => {
    const toggleView = () => onSetIndex(isSelected ? '' : index);
    const listPaddingStyle = {
        padding: `${listPadding} 0`
    };

    const shouldShow = isSelected || !isExpandable;
    const componentVariables = {
        'background-color': shouldShow && selectedBackgroundColor
    };

    return (
        <div {...n('selectedBackground').withVariables(componentVariables).withTestId().props}>
            <div {...n('QAgroup').props}>
                <div
                    {...n('listText').withTestId().props}
                    onClick={toggleView}
                    onKeyDown={null}
                    style={listPaddingStyle}
                >
                    <div
                        {...n('faqDataContainer', [
                            isSelected && 'is-selected',
                            isExpandable && 'is-expandable'
                        ]).withTestId().props}
                    >
                        <div>{faqData.question}</div>
                        {isExpandable && (
                            <div {...n('caretContainer').props}>
                                <Icon
                                    onClick={toggleView}
                                    type={isSelected ? 'caretUp' : 'caretDown'}
                                    {...n('caret').props}
                                />
                            </div>
                        )}
                    </div>
                    {shouldShow && (
                        <div
                            {...n('textContainer').withTestId().props}
                            dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(faqData.answer) }}
                        />
                    )}
                </div>
            </div>
        </div>
    );
};
export default Collapsible;

Collapsible.propTypes = {
    listPadding: PropTypes.number,
    isExpandable: PropTypes.bool,
    isSelected: PropTypes.bool,
    index: PropTypes.number,
    onSetIndex: PropTypes.func,
    selectedBackgroundColor: PropTypes.string,
    faqData: PropTypes.shape({
        answer: PropTypes.string,
        question: PropTypes.string
    }).isRequired
};
Collapsible.defaultProps = {
    listPadding: 1,
    isExpandable: false,
    onSetIndex: () => (1),
    isSelected: true,
    index: 1,
    selectedBackgroundColor: '#F7F7F7'
};
