import React, { useState, useEffect } from 'react';
import DOMPurify from 'dompurify';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { generateUniqueID } from '../../tools/helpers';
import Icon from '../icon/Icon';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/CollapsibleText.scss';

const n = createNamespace('CollapsibleText');

const Collapsible = ({
    faqData,
    listPadding,
    isActive,
    isExpandable,
    selectedBackgroundColor,
    setActiveCollapsibleIndex,
    focusable,
    index
}) => {
    // isActive makes it possible to close the collapsible from outside the component
    // (for example, the collapsible is part of a group of collapsibles in the faq).
    // If isActive is not used (defaults to true), then only isOpen matters.
    const [isOpen, setIsOpen] = useState(true);
    const toggleView = () => {
        const newState = !isOpen;
        setActiveCollapsibleIndex(newState ? index : null);
        setIsOpen(newState);
    };
    const listPaddingStyle = {
        padding: `${listPadding}px 0`
    };

    useEffect(() => {
        if (!isActive) {
            setIsOpen(false);
        }
    }, [isActive, setIsOpen]);

    const isExpanded = isActive && isOpen;
    const componentVariables = {
        'background-color': isExpanded && selectedBackgroundColor
    };
    const uid = generateUniqueID([faqData.question]);

    return (
        <div {...n('selectedBackground').withVariables(componentVariables).withTestId().props}>
            <div {...n('QAgroup').props}>
                <div
                    {...n('listText').withTestId().props}
                    style={listPaddingStyle}
                >
                    {isExpandable ? (
                        <h3 {...n('question').withTestId().props}>
                            <button
                                disabled={!focusable}
                                aria-expanded={isExpanded ? 'true' : 'false'}
                                aria-controls={uid}
                                {...n('toggleButton').withTestId().props}
                                type="button"
                                onClick={toggleView}
                                onKeyDown={null}
                                tabIndex={focusable ? 0 : -1}
                            >
                                {faqData.question}
                                <div {...n('caretContainer').props}>
                                    <Icon
                                        type={isExpanded ? 'caretUp' : 'caretDown'}
                                        {...n('caret').props}
                                    />
                                </div>
                            </button>
                        </h3>
                    ) : (
                        <h3 {...n('question').withTestId().props}>{faqData.question}</h3>
                    )}
                    <div
                        aria-hidden={isExpandable && !isExpanded}
                        hidden={isExpandable && !isExpanded}
                        id={uid}
                        {...n('textContainer', (isExpandable && !isExpanded) && 'hidden').withTestId().props}
                        dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(faqData.answer) }}
                    />
                </div>
            </div>
        </div>
    );
};
export default Collapsible;

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