import * as React from "react";

const { useState } = React;

interface SearchBoxProps {
  initialValue: string;
  onSearch: Function;
}

type ChangeEvent = React.ChangeEvent<HTMLInputElement>;
type ClickEvent = React.MouseEvent<HTMLInputElement>;

export const SearchBox = ({
  initialValue,
  onSearch
}: SearchBoxProps): JSX.Element => {
  const [value, setValue] = useState(initialValue || "");

  const onChange = (event: ChangeEvent) => {
    setValue(event.target.value);
  };

  const onClick = (_event: ClickEvent) => {
    onSearch(value);
  };

  const onClear = (_event: ClickEvent) => {
    setValue("");
    onSearch("");
  };

  return (
    <div className="searchform">
      <label htmlFor="search">Search: </label>
      <input type="text" name="search" value={value} onChange={onChange} />
      <input type="button" name="send" value="Search" onClick={onClick} />
      <input type="button" name="clear" value="clear" onClick={onClear} />
    </div>
  );
};
