/**
 * A menu strip showing all L1 categories in the system in desktop view
 *
 * @param {object} categoriesTree - a list of CategoryTreeNodeModel, each element denotes a tree node in the categories tree structure.
 */

import { Component } from 'react'
import { Link } from 'react-router-dom'
import { Popover, PopoverBody } from 'reactstrap'
import NavigationMenu from './NavigationMenu'
import urlGenerator from '$ustoreinternal/services/urlGenerator'
import { decodeStringForURL } from '$ustoreinternal/services/utils'
import { t } from '$themelocalization'
import './CategoriesNavbar.scss'
import { getVariableValue } from '$ustoreinternal/services/cssVariables'

class CategoriesNavbar extends Component {
  constructor (props) {
    super(props)

    this.mouseOverElement = false
    this.categoryChanged = false

    this.state = {
      selectedCategory: null,
      isOverlayOpen: false,
      popoverTarget: 'id-0',
      keepNavigationOpen: false,
      isHover: false,
      lastHover: ''
    }
  }

  handleMouseOut () {
    if (!this.state.keepNavigationOpen) {
      this.mouseOverElement = false

      // close popover with delay to handle a case where mouse is already over another element
      setTimeout(() => {
        if (!this.mouseOverElement) {
          this.setState({ selectedCategory: null, isOverlayOpen: false })
        } else {
          // if mouse is already over another element check if the category has changed - if so close the popover and open again (for refresh), else do nothing
          if (this.categoryChanged) {
            this.setState({ isOverlayOpen: false })
            if (this.state.selectedCategory.HasSubCategories || this.state.selectedCategory?.FriendlyID === 0) // handeling the case when popover shouldn't open because there are no sub categories
            { this.setState({ isOverlayOpen: true }) }
          }
        }
      }, 5)
    }
  }

  handleMouseOver (category) {
    this.mouseOverElement = true

    // if !category its the popover - dont do anything
    if (!category) { return }

    this.categoryChanged = !this.state.selectedCategory || (this.state.selectedCategory.FriendlyID !== category.FriendlyID)

    this.setState({ selectedCategory: category })

    // if category doesn't have sub categories or its the popover - return
    if ((category && !category.HasSubCategories && category.FriendlyID !== 0)) { return }

    const popoverTarget = `id-${category.FriendlyID}`
    this.setState({ popoverTarget, isOverlayOpen: true })

    const popover = document.querySelector('#popover-wrapper .show > div')
    if (!popover) {
      return
    }
    const nextTarget = document.getElementById(popoverTarget)
    const nextTargetRect = nextTarget.getBoundingClientRect()
    const m = popover.style.transform.match(/translate\(\s*\d+[a-z]{0,3}\s*,\s*(\d+[a-z]{0,3})\s*\)/)
    const currentTop = m ? m[1] : '61px'
    popover.style.transform = `translate(${nextTargetRect.x}px, ${currentTop})`
  }
  
    hoverMouseOver(item,no) {
    if (!item) { return }
    this.setState({ isHover: true });
    this.setState({ lastHover: 'custMenu'+no });
  }
  hoverMouseOut() {
    this.setState({ isHover: false });
    this.setState({ lastHover: '' })
  }

  render () {
    const { categoriesTree } = this.props
    if (!(categoriesTree && categoriesTree.length > 0)) {
      return null
    }

    const selected = this.state.selectedCategory
    const viewShowAll = selected && selected.FriendlyID === 0

    //get extra menu items here
    const addMenuPosition = getVariableValue('--cust-menu-position', 'End');
    const addMenu1text = getVariableValue('--cust-menu1-text', '');
    const addMenu1url = getVariableValue('--cust-menu1-url', '');
    const addMenu2text = getVariableValue('--cust-menu2-text', '');
    const addMenu2url = getVariableValue('--cust-menu2-url', '');
    const addMenu3text = getVariableValue('--cust-menu3-text', '');
    const addMenu3url = getVariableValue('--cust-menu3-url', '');
    let addLink1;
    if (addMenu1text.length > 0 && addMenu1url.substring(0,4).toLowerCase() === 'http') {
      addLink1 = <a className='category-title-wrapper' href={addMenu1url}><span id='custMenu1' className={this.state.isHover && this.state.lastHover === 'custMenu1' ? 'category-title highlight' : 'category-title'} onMouseOver={() => this.hoverMouseOver(addMenu1text, '1')} onMouseOut={() => this.hoverMouseOut()}><span className='link'>{addMenu1text}</span></span></a>
    }
    let addLink2;
    if (addMenu2text.length > 0 && addMenu2url.substring(0,4).toLowerCase() === 'http') {
      addLink2 = <a className='category-title-wrapper' href={addMenu2url}><span id='custMenu2' className={this.state.isHover && this.state.lastHover === 'custMenu2' ? 'category-title highlight' : 'category-title'} onMouseOver={() => this.hoverMouseOver(addMenu2text, '2')} onMouseOut={() => this.hoverMouseOut()}><span className='link'>{addMenu2text}</span></span></a>
    }
    let addLink3;
    if (addMenu3text.length > 0 && addMenu3url.substring(0,4).toLowerCase() === 'http') {
      addLink3 = <a className='category-title-wrapper' href={addMenu3url}><span id='custMenu3' className={this.state.isHover && this.state.lastHover === 'custMenu3' ? 'category-title highlight' : 'category-title'} onMouseOver={() => this.hoverMouseOver(addMenu3text, '3')} onMouseOut={() => this.hoverMouseOut()}><span className='link'>{addMenu3text}</span></span></a>
    }

    return (
      <div className="categories-navbar">
        <div className="category-title-wrapper" onMouseEnter={() => this.handleMouseOver({ FriendlyID: 0 })} onMouseLeave={() => this.handleMouseOut()}>
          <span className={`category-title ${selected && selected.FriendlyID === 0 ? 'highlight' : ''}`} id="id-0">
            {t('Header.All_Categories')}
          </span>
        </div>
        {addMenuPosition.toLowerCase() === 'start' && addLink1}
        {addMenuPosition.toLowerCase() === 'start' && addLink2}
        {addMenuPosition.toLowerCase() === 'start' && addLink3}
        {
          categoriesTree.map(({ Category }, i) => {
            const { FriendlyID, Name } = Category
            return <Link className="category-title-wrapper" onMouseEnter={() => this.handleMouseOver(Category)} onMouseLeave={() => this.handleMouseOut()}
              key={i} to={urlGenerator.get({ page: 'category', id: FriendlyID, name: decodeStringForURL(Name) })} >
                <span className={`category-title ${selected && selected.FriendlyID === FriendlyID ? 'highlight' : ''}`} key={i} id={`id-${FriendlyID}`}>
                  <span className="link" key={i} dangerouslySetInnerHTML={{ __html: Name }}/>
                </span>
            </Link>
          })
        }

        <div id="popover-wrapper" className="popover-wrapper" />

        {
          selected &&
          <div onMouseEnter={() => this.handleMouseOver()} onMouseLeave={() => this.handleMouseOut()} keep-navigation-open={`${this.state.keepNavigationOpen}`}>
            <Popover className={viewShowAll ? 'view-show-all' : ''} container={"popover-wrapper"} fade={false} isOpen={this.state.isOverlayOpen} placement="bottom-start" target={this.state.popoverTarget}>
              <PopoverBody>
                <NavigationMenu categoriesTree={categoriesTree} viewShowAll={viewShowAll} selectedCategory={selected} />
              </PopoverBody>
            </Popover>
          </div>
        }
        {addMenuPosition.toLowerCase() !== 'start' && addLink1}
        {addMenuPosition.toLowerCase() !== 'start' && addLink2}
        {addMenuPosition.toLowerCase() !== 'start' && addLink3}
      </div>
    )
  }
}

export default CategoriesNavbar
