import styles from "./styles.module.scss";
import {ChangeEvent, useEffect, useState} from "react";
import {Photo} from "../../types";
import api from "../../api";

type SearchProps = {
  onFilter: (filtered: Photo[]) => void;
}

export default function Search({
  onFilter,
}: SearchProps) {
  const [photos, setPhotos] = useState<Photo[]>([]);
  const [value, setValue] = useState("");

  useEffect(() => {
    api
      .getPhotos()
      .then(setPhotos);
  }, []);

  useEffect(() => {
    const filtered = photos.filter(photo => photo.title.includes(value));
    onFilter(filtered);
  }, [value]);

  const onChange = (e: ChangeEvent<HTMLInputElement>) => {
    const element = e.currentTarget as HTMLInputElement;
    const value = element.value;

    setValue(value);
  }

  return (
    <input
      value={value}
      onChange={onChange}
      type="text"
      placeholder="Search by title"
      className={styles.searchInput}
    />
  )
}