import { ReactElement } from 'react';
import { fetchTagsAndPagesForQuery, Page, PageSortOrder } from '../db/pages';
import FlexView from './flexView/FlexView';
import { logger } from '../utils/logger';
import { useLiveQuery } from 'dexie-react-hooks';
import { useAppSelector } from '../store/hooks';
import { selectQueryTokens } from '../store/uiSlice';

// interface SearchResultProps {
//   queryTokens: string[];
// }

const SearchResult = (): ReactElement => {
  // const result = useLiveQuery(
  //   monitorAsync(() => selectTagsAndPagesForQuery(queryTokens), "selectTagsAndPagesForQuery"),
  //   [queryTokens]
  // );

  // Support just one query at a time for now, not multiple tabs
  const queryTokens = useAppSelector(selectQueryTokens);

  const result = useLiveQuery(
    () => {
      if (!queryTokens || queryTokens.length === 0) return;
      return fetchTagsAndPagesForQuery(queryTokens).then((result) => {
        logger.debug("[SearchResult]", queryTokens, result);
        return result;
      });
    },
    [queryTokens]
  );
  const { tags, pages } = result || { tags: [], pages: [] };
  const tagNames = tags.map((tag) => tag.name);
  const filteredPages = pages?.filter(
    (page) => !page.humanTags.some((tag) => tagNames.includes(tag))
  );

  return (
    <FlexView
      tags={tags}
      overrideExpandedTags={tags}
      pages={filteredPages}
      defaultSortBy={PageSortOrder.recent}
    />
  );
};

export default SearchResult;
