import React, { useEffect, useState } from "react";
import {
  FormControl,
  IconButton,
  Input,
  InputAdornment,
  InputLabel,
} from "@material-ui/core";
import SearchIcon from "@material-ui/icons/Search";
import clsx from "clsx";

const SearchField = (props) => {
  const { classes, onSearch, savedSearchValue } = props;
  const [searchTerm, setSearchTerm] = useState("");
  const handleChange = (e) => {
    setSearchTerm(e.target.value);
  };
  const handleSearch = (e) => {
    if (!onSearch) return;
    onSearch(searchTerm);
  };
  const handleEnterPress = (e) => {
    if (e.keyCode === 13) {
      e.preventDefault();
      handleSearch(e);
    } else if (e.keyCode === 27) {
      e.preventDefault();
      setSearchTerm("");
    }
  };

  useEffect(() => {
    if (savedSearchValue) {
      setSearchTerm(savedSearchValue);
    }
  }, [savedSearchValue]);

  return (
    <FormControl className={clsx(classes.margin, classes.fullWidth)}>
      <InputLabel htmlFor="search">Search</InputLabel>
      <Input
        id="search"
        type="text"
        value={searchTerm}
        onChange={handleChange}
        onKeyDown={handleEnterPress}
        endAdornment={
          <InputAdornment position="end">
            <IconButton aria-label="search" onClick={handleSearch}>
              <SearchIcon />
            </IconButton>
          </InputAdornment>
        }
      />
    </FormControl>
  );
};

export default SearchField;
