import React, { useContext, useRef, useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { navigate } from 'gatsby';
import { FaSearch } from '@react-icons/all-files/fa/FaSearch';
import { leftTrim } from '~helpers/strings';

import { toggleScroll } from '~helpers/scroll';

import { NavigationContext } from '../navigation/navigationContext';

import styles from './search.module.scss';

const SearchForm = ({ className, searchIcon, iconWidth = 24, iconHeight = 24 }) => {
  const { showSearch, setShowSearch, setShowMenu, showMenu } = useContext(NavigationContext);
  const [searchBoxQuery, setSearchBoxQuery] = useState();
  const searchInputRef = useRef();

  const handleOnSearchIconClick = () => {
    setShowSearch(!showSearch);

    toggleScroll('search');

    if (showMenu) {
      setShowMenu(false);
      toggleScroll('menu');
    }
  };

  const handleOverlayClickClose = (event) => {
    if (event.target.classList.contains(styles.searchForm)) {
      toggleScroll('search');
      setShowSearch(false);
    }
  };

  const formSubmitBoxHandler = (e) => {
    e.preventDefault();
    if (searchBoxQuery === '') {
      e.target.querySelector('input').focus();
    } else {
      navigate(`/s?s=${searchBoxQuery}`);
    }
  };

  useEffect(() => {
    // eslint-disable-next-line no-unused-expressions
    showSearch && searchInputRef.current.focus();
  }, [showSearch]);

  return (
    <div className={className || ''}>
      <button
        type="button"
        aria-label="Search"
        onClick={handleOnSearchIconClick}
        className={`${styles.searchButton || ''} ${
          showSearch && (styles.active || '')
        } search-gtm btn-cta`}
      >
        {searchIcon === null ? (
          <FaSearch title="Search Icon" />
        ) : (
          <img alt="Search Icon" src={searchIcon} width={iconWidth} height={iconHeight} />
        )}
        {styles.close && <span className={styles.close || ''} />}
      </button>
      {showSearch && (
        <div
          onClick={handleOverlayClickClose}
          onKeyDown={handleOverlayClickClose}
          tabIndex={0}
          role="button"
          aria-label="Close search"
          className={`${styles.searchForm || ''} ${styles.show || ''}`}
        >
          <form onSubmit={formSubmitBoxHandler} className={styles.form || ''}>
            <input
              type="text"
              aria-label="Søk spill eller casino her"
              placeholder="Søk spill eller casino her"
              className={styles.formInput || ''}
              maxLength="60"
              ref={searchInputRef}
              onChange={(e) => setSearchBoxQuery(leftTrim(e.target.value))}
            />
            <div className={styles.searchButton || ''}>
              <button aria-label="Search" type="submit" className="search-gtm btn-cta">
                {searchIcon === null ? <FaSearch /> : <img alt="search" src={searchIcon} />}
              </button>
            </div>
          </form>
        </div>
      )}
    </div>
  );
};

SearchForm.propTypes = {
  className: PropTypes.string.isRequired,
  searchIcon: PropTypes.string,
  iconWidth: PropTypes.number,
  iconHeight: PropTypes.number,
  pageContext: PropTypes.shape({}),
};

export default SearchForm;
