import Fuse from 'fuse.js';
import React from 'react';

export default function Filter<T, U extends React.ReactNode>({
  items,
  query = '',
  isCaseSensitive = false,
  keys,
  output,
}: {
  items: Array<T>,
  query: string,
  isCaseSensitive?: boolean,
  keys: Array<string>,
  output: (filteredItems: Array<Fuse.FuseResult<T>>) => U,
}) {
  if (query.length > 0) {
    const fuse = new Fuse(items, {
      isCaseSensitive,
      keys,
    });
    const filteredItems = fuse.search<T>(query);
    return (
      <>{output(filteredItems)}</>
    );
  }
  return (
    <>
      {output(items.map((item, refIndex) => ({
        item,
        refIndex,
      })))}
    </>
  );
}
