// @flow
import React from 'react';
import styled from 'styled-components';
import SearchBar from '../SearchBar/SearchBar';

type Props = {
  className?: string,
};

const WideSearch = styled.form`
  width: 100%;
  display: flex;
`;

const SearchBarCentered = styled(SearchBar)`
  margin: auto 0;
`;


const SearchForm = ({ className } : Props) => {
  const textInput = React.createRef();

  const onSearch = (e) => {
    e.preventDefault();
    if (textInput.current !== null) {
      const inputValue = textInput.current.value;
      return window && window.location && window.location.replace(`/search?search=${inputValue}`);
    }
    return null;
  };

  return (
    <WideSearch
      className={`gtm-trackable ${String(className)}`}
      data-gtm-event-context="search-bar-header"
      data-gtm-event-type="form-submission"
      onSubmit={(e) => {
        onSearch(e);
      }}
    >
      <input type="hidden" value="true" />
      <SearchBarCentered textInput={textInput} />
    </WideSearch>
  );
};

SearchForm.defaultProps = {
  className: '',
};

export default SearchForm;
