/* eslint-disable array-callback-return */
import React from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../../../tools/namingTools';

import { getHeaderNavigationVariables } from '../../../../tools/components/header';
import { headerNavigationBarSettingsShape, headerNavigationBarDataShape } from '../../../../constants/components/prop-types/header';
import { headerNavigationBarDefaultSettings, headerNavigationBarDefaultData, headerNavigationBarSchemaForm } from '../../../../constants/components/schemas/header';
import withListener from '../../../withListener';
import { SEARCH_BAR_IN_NAV_BAR } from '../../../../constants/components/header';
import { menusPropTypes } from '../../../../constants/components/prop-types/menu';
import { MENUS } from '../../../../constants/menus';
import HeaderNavigation from '../common/header-navigation/HeaderNavigation';
import HeaderSearchBar from '../common/header-search-bar/HeaderSearchBar';
import { useResponsive } from '../../../../tools/widths/useResponsive';
import { getOnlyProductLines, isSameProductLineEntry, getNavigationBarPrevData, getFormattedProductLinesData } from '../common/header-navigation-utils/headerNavigationUtils';
import './styles/HeaderNavigationBar.scss';

const n = createNamespace('HeaderNavigationBar');

export const mergeNavigationBarData = (productLines, navigationBarData) => {
    const onlyInProductLines = productLines && navigationBarData
        ? getOnlyProductLines(productLines, navigationBarData, isSameProductLineEntry)
        : [];
    const result = [
        ...getNavigationBarPrevData(productLines, navigationBarData),
        ...getFormattedProductLinesData(onlyInProductLines)
    ];
    return result;
};

export const renderNavBarItems = (secondaryItemsFiltered, navBarItems) => (
    (navBarItems && navBarItems.length > 1) ? navBarItems
        : mergeNavigationBarData(secondaryItemsFiltered, navBarItems));

const HeaderNavigationBar = ({
    data: {
        searchBar,
        categories,
        config,
        nav,
        toggleHeaderScrimFunction
    },
    settings,
    menus
}) => {
    const settingsWithDefaults = {
        ...HeaderNavigationBar.defaultProps.settings,
        ...settings
    };
    const {
        navBarTextAlignment,
        navBarTextSize,
        searchBackgroundColor,
        searchIconColor,
        searchButtonColor,
        searchBorderColor,
        searchBarMaxWidth,
        searchBorderVisible,
        searchCornerRadius,
        searchIcon,
        searchPlaceholder: settingSearchPlaceholder,
        searchBarHeight,
        searchBarLocation
    } = settingsWithDefaults;

    const { mediumDown: isMobile } = useResponsive();
    const componentVariables = getHeaderNavigationVariables(settings);
    const wrapperModifiers = [navBarTextSize && `text-size-${navBarTextSize}`];

    const {
        label: searchBarLabel,
        placeholder: searchBarPlaceholder
    } = searchBar;

    const searchBarProps = {
        ...n('searchBar').props,
        searchBackgroundColor,
        searchBorderColor,
        searchCornerRadius,
        searchBorderVisible,
        searchIconColor,
        searchButtonColor,
        searchIcon,
        label: searchBarLabel,
        searchPlaceholder: settingSearchPlaceholder || searchBarPlaceholder,
        searchBarMaxWidth,
        searchBarHeight
    };

    const displaySearchBar = searchBarLocation === SEARCH_BAR_IN_NAV_BAR.value;

    const navBarItems = menus && menus[MENUS.NAVIGATION_BAR_MENU] && menus[MENUS.NAVIGATION_BAR_MENU].menu;

    const secondaryItems = nav && nav.secondary ? nav.secondary.items : [];
    const secondaryItemsFiltered = secondaryItems.reduce((filtered, item) => {
        if (!item.key) {
            const { href } = item;
            const id = parseInt((href.split('=')[1]), 10);
            filtered.push({ ...item, id });
        }
        return filtered;
    }, []);

    return (
        !isMobile && (
            <div {...n('navigationBar').withTestId().props}>
                <div {...n('wrapper', wrapperModifiers).withVariables(componentVariables).withTestId().props}>
                    <div {...n('content').props}>
                        <HeaderNavigation
                            {...n('navigation').props}
                            items={renderNavBarItems(secondaryItemsFiltered, navBarItems)}
                            align={navBarTextAlignment}
                            textSize={navBarTextSize}
                            withMoreButton
                            categories={categories}
                            categoriesMenuSettings={settings}
                            listingEndpoint={config.listingEndpoint}
                            locale={config && config.locale}
                            toggleHeaderScrimFunction={toggleHeaderScrimFunction}
                            menuType={MENUS.NAVIGATION_BAR_MENU}
                        />
                        {displaySearchBar && (
                            <HeaderSearchBar settings={searchBarProps} data={{ ...config }} />
                        )}
                    </div>
                </div>
            </div>
        )
    );
};

HeaderNavigationBar.schema = () => ({
    name: 'Header Navigation Bar',
    title: 'uieditor.sfbComponent.header.navigationBar.title',
    iconName: 'hamburger',
    form: headerNavigationBarSchemaForm
});

HeaderNavigationBar.propTypes = {
    data: PropTypes.shape(headerNavigationBarDataShape),
    settings: PropTypes.shape(headerNavigationBarSettingsShape),
    menus: PropTypes.shape(menusPropTypes)
};

HeaderNavigationBar.defaultProps = {
    data: headerNavigationBarDefaultData,
    settings: headerNavigationBarDefaultSettings,
    menus: menusPropTypes
};

export default withListener(HeaderNavigationBar);
