/**
 *
 * NavigationBar
 *
 */

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { compose } from 'redux';
import { loadItem } from 'services/localStorageApi';
import { intlShape, injectIntl } from 'react-intl';
import { withRouter } from 'react-router-dom';
import { get } from 'lodash';
import CapNavigation from '@capillarytech/cap-ui-library/CapNavigation';
import { CAP_WHITE } from '@capillarytech/cap-ui-library/styled/variables';
import injectSaga from '../../utils/injectSaga';
import sagas from './saga';
import messages from './messages';
import { LOYALTY } from '../../v2Containers/App/constants';
import {
  HELP_URL,
  LOYALTY_HELP_URL,
  DEFAULT_MODULE,
  AI_DOCUMENTATION_BOT_DISABLED,
} from '../../v2Containers/Cap/constants';
import configPath from '../../config/path';
import * as Api from '../../services/api';
import { CapLeftNavigatioOpenCss, CapLeftNavigationCss } from './style';
import { EMBEDDED } from './constants';

const CapWrapper = styled.div`
  position: absolute;
  padding: 0;
  background-color: ${CAP_WHITE};
  width: 100%;
  display: flex;
  margin-top: ${(props) => props.isEmbedded ? '0px' : '64px'};

  .sidebar-container {
    margin-right: 10px;
  }
  .ant-collapse {
    background-color: ${CAP_WHITE};
  }
`;

const ComponentWrapper = styled.div`
  max-width: 1140px;
  margin: 0 auto;
  width: 100%;
  padding: 24px 0;
`;

export class NavigationBar extends React.Component {
  constructor(props) {
    super(props);
    this.state = this.initializeSelectedProduct();
  }

  initializeSelectedProduct = () => {
    const { location, intl: { formatMessage } } = this.props;
    const { pathname } = location;
    const parentModule = pathname.substring(pathname.lastIndexOf('/') + 1);
    switch (parentModule) {
      case LOYALTY:
        return {
          selectedProduct: formatMessage(messages.loyaltyProgram),
          helpUrl: LOYALTY_HELP_URL,
        };
      default:
        return {
          selectedProduct: formatMessage(messages.selectedProductDefault),
          helpUrl: HELP_URL,
        };
    }
  }

  onOrgSettingsClick = () => {
    const { orgSettingsUrl } = this.props;
    if (orgSettingsUrl) {
      window.open(orgSettingsUrl, '_blank');
    }
  };

  onHelpIconClick = () => {
    const { helpUrl } = this.state;
    if (helpUrl) {
      window.open(helpUrl, '_blank');
    }
  };

  getTopbarIcons = (showDocumentationBot = false) => {
    const ICONS = [
      {
        iconType: 'help',
        key: 'help',
        onClickHandler: this.onHelpIconClick,
      },
    ];
    return showDocumentationBot ? ICONS.slice(1) : ICONS; // If showDocumentationBot is true, help icon will be replaced by Aira icon on UI
  };

  getDropdownMenu = () => {
    const { formatMessage } = this.props.intl;
    return [
      {
        label: formatMessage(messages.orgSettings),
        key: formatMessage(messages.orgSettings),
        onClickHandler: this.onOrgSettingsClick,
      },
      {
        label: formatMessage(messages.logout),
        key: formatMessage(messages.logout),
        onClickHandler: this.props.logout,
      },
    ];
  };

  handleOrgChange = (orgId) => {
    const selectedOrg = loadItem('orgID');
    if (selectedOrg !== orgId) {
      this.props.changeOrg(orgId);
    }
  };

  productSelection = () => {
    const { location, intl: { formatMessage } } = this.props;
    const { pathname } = location;
    const parentModule = pathname.substring(pathname.lastIndexOf('/') + 1);
    switch (parentModule) {
      case LOYALTY:
        return formatMessage(messages.loyaltyProgram);
      default:
        return formatMessage(messages.selectedProductDefault)
    }
  }

  render() {
    const {
      topbarMenuData,
      type,
      userData,
      intl,
      handleLeftNavBarExpanded,
      leftNavbarExpandedProp,
    } = this.props;

    const accessibleDocFeatures = get(userData, 'currentOrgDetails.accessibleFeatures', []);
    const showDocumentationBot = !accessibleDocFeatures.includes(AI_DOCUMENTATION_BOT_DISABLED);

    const dropdownMenuProps = this.getDropdownMenu();
    const topbarIcons = this.getTopbarIcons(showDocumentationBot);
    const headerOverideCss = leftNavbarExpandedProp ? CapLeftNavigatioOpenCss : CapLeftNavigationCss;
    return (
      <CapNavigation
        className="creatives-main-container"
        showContent
        userData={userData}
        loadStorageItem={loadItem}
        changeOrgEntity={this.handleOrgChange}
        topbarMenuData={topbarMenuData}
        topbarSelectedMenuData={[DEFAULT_MODULE]}
        dropdownMenuProps={dropdownMenuProps}
        topbarIcons={topbarIcons}
        sidebarMenuData={[]}
        sidebarMenuItemsPosition={null}
        defaultSelectedProduct={this.productSelection()}
        skipStateForStorage
        selectOrganization={intl.formatMessage(messages.selectOrganization)}
        isLatestLeftNavigationEnabled
        history={history}
        publicPath={configPath.publicPath}
        getNavigationConfigApi={Api.getNavigationConfigApi}
        showDocumentationBot={showDocumentationBot}
        setLeftNavbarExpandedProp={handleLeftNavBarExpanded}
        headerOverideCss={headerOverideCss}
        request={Api?.request}
        getAPICallObject={Api?.getAPICallObject}
      >
        <div data-testid="cap-wrapper">
          <CapWrapper isEmbedded={type === EMBEDDED}>
            <ComponentWrapper>
              {React.Children.toArray(this.props.children)}
            </ComponentWrapper>
          </CapWrapper>
        </div>
      </CapNavigation>

    );
  }
}

NavigationBar.propTypes = {
  userData: PropTypes.object,
  topbarMenuData: PropTypes.array,
  logout: PropTypes.func,
  changeOrg: PropTypes.func,
  children: PropTypes.node,
  orgSettingsUrl: PropTypes.string,
  intl: intlShape.isRequired,
  location: PropTypes.object,
  type: PropTypes.string,
  handleLeftNavBarExpanded: PropTypes.func,
  leftNavbarExpandedProp: PropTypes.bool,
};

const withSagas = sagas.map((saga) => injectSaga(saga));
export default compose(...withSagas)(withRouter(injectIntl(NavigationBar)));
