import React from 'react';
import PropTypes from 'prop-types';
import { generateUniqueID } from '../../tools/helpers';
import { createNamespace } from '../../tools/namingTools';
import { THEME_PRIMARY } from '../../constants/buttons';
import Link from '../link/Link';
import './styles/SideBar.scss';

const n = createNamespace('sideBar');

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 renderLink = ({ label, href, id }) => (
        <div key={generateUniqueID([id, label, href])}>
            {href ? (
                <Link {...n('groupLink').withTestId().withE2EId().props} theme={THEME_PRIMARY} href={href}>{label}</Link>
            ) : label}
        </div>
    );

    const renderItem = ({ title, items: links }, index) => (
        <div {...n('textGroup').withTestId().withE2EId().props} key={generateUniqueID([title, index])}>
            {title && (
                <div {...n('groupTitle').withTestId().withE2EId().props}>{title}</div>
            )}
            {Boolean(links && links.length) && links.map(renderLink)}
        </div>
    );

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

    return (
        <div {...n('container').withVariables(componentVariables).withTestId().withE2EId().props}>
            {navItems.map(renderSection)}
        </div>
    );
};

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

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

export default SideBar;
