import React, { useState } from 'react';
import PropTypes from 'prop-types';
import withListener from '../../../withListener';
import { headerAuxBarDefaultSettings, headerAuxBarSchemaForm } from '../../../../constants/components/schemas/header';
import { headerAuxBarSettingsShape, headerAuxBarDataShape } from '../../../../constants/components/prop-types/header';
import { menusPropTypes } from '../../../../constants/components/prop-types/menu';
import { SECTIONS } from '../../../../constants/namespaces';
import { MENUS } from '../../../../constants/menus';
import { createNamespace } from '../../../../tools/namingTools';
import { darken } from '../../../../tools/colorHelper';
import { getPropValue } from '../../../../tools/objectTools';
import { useResponsive } from '../../../../tools/widths/useResponsive';
import { resolveHeaderBarTokens } from '../../../../tools/companyBranding';
import Link from '../../../../atoms/link/Link';
import LanguageSwitcher from '../../../../atoms/language-switcher/LanguageSwitcher';
import MenuDropdown from '../../../../atoms/menu-dropdown/menuDropdown';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/HeaderAuxiliaryBar.scss';

const n = createNamespace('HeaderAuxiliaryBar');

let timer;

const resetAutoCloseTimer = () => {
    clearTimeout(timer);
};

const HeaderAuxiliaryBar = ({
    data: {
        locale,
        i18n,
        pageId,
        config
    },
    settings,
    menus
}) => {
    const settingsWithDefaults = {
        ...HeaderAuxiliaryBar.defaultProps.settings,
        ...settings
    };

    const {
        auxBarHeight,
        auxBarBackgroundColor,
        auxBarTextColor,
        auxBarTextColorHover,
        auxBarBorderColor,
        auxBarTextSize,
        auxBarTextAlignment,
        displayLanguageSwitcher,
        auxBarLinkSpacing
    } = settingsWithDefaults;
    const { mediumDown: isMobile } = useResponsive();
    const [openSubmenus, setOpenSubmenus] = useState();

    const {
        backgroundColor: effectiveBackgroundColor,
        textColor: effectiveTextColor,
        hoverColor: effectiveHoverColor,
        borderColor: effectiveBorderColor
    } = resolveHeaderBarTokens({
        brandingContext: config?.brandingContext,
        backgroundColor: auxBarBackgroundColor,
        textColor: auxBarTextColor,
        hoverColor: auxBarTextColorHover,
        borderColor: auxBarBorderColor
    });

    const styleVariables = {
        height: auxBarHeight && `${auxBarHeight}px`,
        'background-color': effectiveBackgroundColor,
        'border-color': effectiveBorderColor,
        'text-color': effectiveTextColor,
        'text-color-hover': effectiveHoverColor,
        'item-spacing': auxBarLinkSpacing && `${auxBarLinkSpacing / 2}px`,
        'lang-dropdown-bg-color': effectiveBackgroundColor && darken(effectiveBackgroundColor, 0.1)
    };
    const modifiers = [
        auxBarTextSize && `${auxBarTextSize}-text`,
        auxBarTextAlignment
    ];

    const setCloseTimer = () => {
        timer = setTimeout(() => {
            setOpenSubmenus('');
        }, 350);
    };

    const hasMenu = menus && menus[MENUS.AUXILIARY_BAR_MENU] && menus[MENUS.AUXILIARY_BAR_MENU].menu;
    const links = hasMenu && menus[MENUS.AUXILIARY_BAR_MENU].menu.map(menuItem => {
        const { isVisible, openInNewTab, children, uuid } = menuItem;
        const titleText = getPropValue(menuItem, 'title.value');
        const linkUrl = getPropValue(menuItem, 'link.value');

        if (!isVisible || !titleText) {
            return null;
        }
        const hasChildren = children && children.length > 0;
        const target = openInNewTab ? '_blank' : null;
        const showMenuDropDown = items => {
            const visibleChildItems = items && items.filter(item => item.isVisible);
            return items && visibleChildItems.length > 0;
        };

        const setMenuToBeOpened = () => {
            resetAutoCloseTimer();
            setOpenSubmenus(uuid);
        };

        const showSubmenu = openSubmenus === uuid;

        return (
            <li {...n('item').withTestId('linksItem').props} key={uuid}>
                {hasChildren && showMenuDropDown(children) ? (
                    <li
                        {...n('auxBarNavItem', 'user-dropdown').withTestId('userDropdown').props}
                        onMouseOver={setMenuToBeOpened}
                        onFocus={setMenuToBeOpened}
                        onMouseLeave={setCloseTimer}
                        onBlur={setCloseTimer}
                    >
                        <Link
                            href={linkUrl || ''}
                            {...n('link').props}
                            target={target}
                        >
                            {titleText}
                        </Link>
                        <MenuDropdown
                            showSubmenu={showSubmenu}
                            items={children}
                        />
                    </li>
                ) : (
                    <Link
                        href={linkUrl || ''}
                        {...n('link').props}
                        target={target}
                    >
                        {titleText}
                    </Link>
                )}
            </li>
        );
    });

    return (
        !isMobile && (
            <div
                {...n('auxBar').withTestId().props}
                aria-label={i18n.auxNavigation}
                role="navigation"
            >
                <ul {...n('wrapper', modifiers).withVariables(styleVariables).props}>
                    {links}
                    {displayLanguageSwitcher
                        && (
                            <li {...n('item').withTestId('linksItem').props} key="languageSwitcher">
                                <LanguageSwitcher
                                    {...n('languagesSwitcher', auxBarTextSize).props}
                                    {...locale}
                                    i18n={i18n}
                                    pageId={pageId}
                                />
                            </li>
                        )}
                </ul>
            </div>
        )
    );
};

HeaderAuxiliaryBar.defaultProps = {
    data: {
        locale: {
            current: undefined,
            code: undefined,
            available: []
        },
        i18n: {
            auxNavigation: 'Auxiliary Navigation'
        },
        config: {}
    },
    settings: headerAuxBarDefaultSettings,
    menus: menusPropTypes
};

HeaderAuxiliaryBar.schema = () => ({
    name: 'Header Auxiliary Bar',
    title: 'uieditor.sfbComponent.header.auxiliaryBar.title',
    iconName: 'ellipsis',
    form: headerAuxBarSchemaForm,
    orderableSection: [SECTIONS.header],
    childrenOrderableComponent: true
});

HeaderAuxiliaryBar.propTypes = {
    settings: PropTypes.shape(headerAuxBarSettingsShape),
    data: PropTypes.shape(headerAuxBarDataShape),
    menus: menusPropTypes
};

export default withListener(HeaderAuxiliaryBar);
