/**
 * This component represents the search text box in the header
 * When searching - the store redirects to the 'Search' page with results from the input
 *
 * @param {object} customState - custom state of store
 */

import React, { useEffect, useState } from 'react';
import { useNavigate, useLocation, useParams } from 'react-router-dom'
import { InputGroup } from 'reactstrap'
import { Icon } from '$core-components'
import urlGenerator from '$ustoreinternal/services/urlGenerator'
import { useUStoreState } from '$ustoreinternal/services/hooks';
import { UStoreProvider } from '@ustore/core'
import { t } from '$themelocalization'
import './Search.scss'

const escapeValue = (value) => value ? value.replace(/[&:<>'"+*?\\/.%#|]/g, " ").trim() : ''

const Search = (props) => {
  const params = useParams()
  const { customState } = useUStoreState()
  const [searchValue, setSearchValue] = useState(params.page === 'search' ? params.id :  '')
  const navigate = useNavigate()
  const location = useLocation()

  useEffect(() => {
    if (window.ga) {
      window.ga('send', 'pageview', location.pathname);
    }
  }, [location])

  const onSearchClicked = () => {
    let value = escapeValue(searchValue)
    if (value.length > 0) {
      UStoreProvider.state.customState.set('searchValue', value)
      navigate(urlGenerator.get({page: 'search', id: decodeURIComponent(value)}))
    }
  }

  const onKeyPress = (event) => {
    if (event.key === 'Enter') {
      onSearchClicked()
      event.preventDefault();
    }
  }

  const onChange = (e) => {
    UStoreProvider.state.customState.delete('searchValue')
    setSearchValue(e.target.value)
  }


  return customState && <div className={`search ${props.className || ''}`}>
    <InputGroup size="normal">
      <input type="text" className="search-input form-control"
             value={searchValue}
             placeholder={t('Search.Search_Products')}
             onChange={onChange}
             onKeyPress={onKeyPress}/>
      <InputGroup className="search-button" onClick={onSearchClicked}>
        <div className="search-icon-container">
          <Icon name="search.svg" width="21px" height="21px" className="search-icon"/>
        </div>
      </InputGroup>
    </InputGroup>
  </div>

}

export default Search
