import React, { useState } from 'react';
import { 
  IonItem, 
  IonList, 
  IonSearchbar,
  IonCard, 
  IonCardHeader,
  IonCardTitle,
} from '@ionic/react';
import capsules from '../data/Capsule.json'


function SearchBar() {

  let [results, setResults] = useState([...capsules]);

  const filterSearch = (ev: Event) => {
    let query = "";
    const target = ev.target as HTMLIonSearchbarElement;
    if (target) query = target.value!.toLowerCase();

    setResults(capsules.filter(cap => {
      return cap.title.toLowerCase().indexOf(query) > -1;
    })
    )
  }

  return (
    <>
      <IonSearchbar debounce={500} onIonChange={(ev) => filterSearch(ev)}></IonSearchbar>

      <IonList inset={true}>
        { results.map(result => (
            <IonCard>
            <IonItem button routerLink={`/Capsule/${result.id}`}>
              <IonCardHeader>
                <IonCardTitle>{result.title}</IonCardTitle>
              </IonCardHeader>
            </IonItem>
          </IonCard>
        ))}
      </IonList>
    </>
  );
}
export default SearchBar;
