import { Query } from './Query';
import * as cacheApi from '@/api/cache/query';
import { memo, useMemo, useState } from 'react';
import type { QueryItem } from 'shared/types/cache';

type QueryListProps = QueryItem;

export const QueryList = memo(({ queries }: QueryListProps) => {
  const [deletedQueries, setDeletedQueries] = useState<QueryItem['queries']>([]);

  const activeQueries = useMemo(
    () => queries.filter((queryKey) => !deletedQueries.includes(queryKey)),
    [deletedQueries, queries]
  );

  function deleteQuery(queryKey: string) {
    cacheApi.deleteQuery(queryKey).then(() => setDeletedQueries([...deletedQueries, queryKey]));
  }

  return activeQueries.map((queryKey) => (
    <Query
      key={queryKey}
      queryKey={queryKey}
      handleDeleteQuery={() => {
        deleteQuery(queryKey);
      }}
    />
  ));
});
