import React from 'react';
import styled from 'styled-components';

import v from '../../styles/Variables';
import InputError from '../Inputs/InputError';

// const SearchIcon = require('../../images/icon--search.svg');

interface Props {
  blurCallback: () => void;
  callback: (e: React.KeyboardEvent<HTMLInputElement>) => string;
  error?: string;
  height?: number;
  id?: string;
  placeholder?: string;
  submitCallback: (v: string) => string;
  value?: string;
  iconTop?: number;
  iconRight?: number;
  ariaactivedescendant: string;
  ariaexpanded: boolean;
  rfkid?: string | null;
}

interface Styles {
  iconTop?: number;
  iconRight?: number;
}

const Search = ({
  blurCallback,
  callback,
  error,
  height = 42,
  id = 'search',
  placeholder = 'What can we help you find?',
  submitCallback,
  value = '',
  iconTop = -2,
  iconRight = 0,
  ariaactivedescendant = '0',
  ariaexpanded = false,
  rfkid = null,
}: Props) => {
  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        submitCallback(value);
      }}
      className="position--relative"
    >
      <label id={`${id}-label`} className="sr-only">
        {id}
      </label>
      <SearchInput
        autoComplete="off"
        type="text"
        id={id}
        name={id}
        placeholder={placeholder}
        height={height}
        defaultValue={value}
        onKeyUp={(e) => callback(e)}
        onBlur={() => blurCallback()}
        aria-describedby={`${id}-instructions`}
        aria-activedescendant={ariaactivedescendant}
        aria-controls="SearchSuggestion"
        aria-expanded={ariaexpanded}
        aria-labelledby={`${id}-label`}
        aria-haspopup="listbox"
        data-rfkid={rfkid}
      />
      <SearchIconStyles iconTop={iconTop} iconRight={iconRight} aria-label={id}>
        <i className="fal fa-search" aria-hidden="true" />
      </SearchIconStyles>
      {error && <InputError error={error} />}
    </form>
  );
};

export default Search;

/* styles */
const SearchInput = styled.input`
  background: ${v.colors.offLight};
  border: none;
  line-height: ${({ height }) => `${height}px`};
  font-size: 14px;
  padding: 0 50px 0 10px;
  width: 100%;
  padding-right: 55px !important;
`;

const SearchIconStyles = styled.button<Styles>`
  position: absolute;
  width: 45px;
  padding: 11px;
  right: ${({ iconRight }) => `${iconRight}px`};
  top: ${({ iconTop }) => `${iconTop}px`};
  border: none;
  background: none;
`;
