import DOMPurify from 'dompurify';
import PropTypes from 'prop-types';
import React from 'react';
import { THEME_PRIMARY } from '../../constants/buttons';
import { generateUniqueID } from '../../tools/helpers';
import { createNamespace } from '../../tools/namingTools';
import Link from '../link/Link';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/SideBar.scss';

const n = createNamespace('sideBar');

// Sanitizes the value and checks if the result contains HTML elements.
// Returns the sanitized string if valid HTML survives, or null otherwise.
// Plain text or values with only stripped tags (e.g., "Size <medium>")
// return null so callers can fall back to plain text rendering.
const sanitizeHtml = value => {
    if (typeof value !== 'string') { return null; }
    const sanitized = DOMPurify.sanitize(value);
    return /<[a-z][\s\S]*>/i.test(sanitized) ? sanitized : null;
};

const SideBar = ({
    navItems,
    headerBackground,
    sideBarBackground,
    sideBarBorder
}) => {
    if (!navItems || !navItems.length) {
        return null;
    }

    const componentVariables = {
        'container-border-color': sideBarBorder,
        'container-background-color': sideBarBackground,
        'header-background-color': headerBackground
    };

    const renderLinkContent = ({ label, href, isHtml }) => {
        if (href) {
            return <Link {...n('groupLink').withTestId().withE2EId().props} theme={THEME_PRIMARY} href={href}>{label}</Link>;
        }
        if (isHtml) {
            const sanitized = sanitizeHtml(label);
            if (sanitized) {
                return <span {...n('htmlContent').props} dangerouslySetInnerHTML={{ __html: sanitized }} />;
            }
        }
        return label;
    };

    const renderLink = ({ label, href, id, isHtml }) => (
        <li {...n('linkWrapper').props} key={generateUniqueID([id, label, href])}>
            {renderLinkContent({ label, href, isHtml })}
        </li>
    );

    const renderItem = ({ title, items: links }, index) => (
        <React.Fragment key={generateUniqueID([title, index])}>
            {title && (
                <dt
                    {...n('groupTitle').withTestId().withE2EId().props}
                >
                    {title}
                </dt>
            )}
            {Boolean(links && links.length) && (
                <dd {...n('linkWrapper').props}>
                    <ul {...n('list').props} aria-label={title}>
                        {links.map(renderLink)}
                    </ul>
                </dd>
            )}
        </React.Fragment>
    );

    const renderSection = ({ title, items }, index) => {
        const uid = generateUniqueID([title, index]);
        return (
            <div {...n('section').withTestId().withE2EId().props} key={uid}>
                {title && (
                    <div {...n('header').withTestId().withE2EId().props}>
                        <h3 {...n('headerText').withTestId().withE2EId().props}>{title}</h3>
                    </div>
                )}
                {Boolean(items && items.length) && (
                    <dl {...n('textContainer').withTestId().withE2EId().props}>
                        {items.map(renderItem)}
                    </dl>
                )}
            </div>
        );
    };

    return (
        <aside {...n('container').withVariables(componentVariables).withTestId().withE2EId().props} aria-label="Sidebar">
            {navItems.map(renderSection)}
        </aside>
    );
};

SideBar.propTypes = {
    navItems: PropTypes.arrayOf(
        PropTypes.shape({
            title: PropTypes.string,
            items: PropTypes.arrayOf(
                PropTypes.shape({
                    label: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
                    href: PropTypes.string,
                    isHtml: PropTypes.bool
                })
            )
        })
    ),
    headerBackground: PropTypes.string,
    sideBarBackground: PropTypes.string,
    sideBarBorder: PropTypes.string
};

SideBar.defaultProps = {
    navItems: null,
    headerBackground: '#F5F5F5',
    sideBarBackground: '#FFFF',
    sideBarBorder: '#CBCBCB'
};

export default SideBar;
