import { type FC, useMemo } from 'react';

import HuList from '@material-hu/components/design-system/List';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';

import PlaceholderState from 'src/pages/dashboard/search/components/PlaceholderState';
import ResultRow from 'src/pages/dashboard/search/components/ResultRow';
import { type SearchFilter } from 'src/pages/dashboard/search/types';

import InfiniteList from 'src/components/list/InfiniteList';
import { NoMoreResultsFooter } from 'src/components/NoMoreResultsFooter';

import { usePaginatedGlobalSearchQuery } from '../queries';

const SKELETON_ROWS = 8;

const SkeletonList: FC = () => (
  <HuList>
    {Array.from({ length: SKELETON_ROWS }).map((_, i) => (
      <HuListItem
        key={i}
        loading
      />
    ))}
  </HuList>
);

type ResultsViewProps = {
  query: string;
  category: SearchFilter;
};

const ResultsView: FC<ResultsViewProps> = ({ query, category }) => {
  const {
    data,
    isLoading,
    isError,
    hasNextPage,
    fetchNextPage,
    isFetchingNextPage,
  } = usePaginatedGlobalSearchQuery(
    query,
    category,
    {
      limit: 20,
    },
    {
      enabled: query.length > 0,
    },
  );

  const results = useMemo(
    () => data?.pages.flatMap(page => page.results) ?? [],
    [data],
  );

  const isEmpty = !isLoading && results.length === 0;
  const showNoMoreResultsFooter =
    !isEmpty && !hasNextPage && !isLoading && data && data.pages.length > 1;

  if (!query) {
    return <PlaceholderState variant="empty" />;
  }

  if (isError) {
    return <PlaceholderState variant="error" />;
  }

  return (
    <>
      <InfiniteList
        isSuccess={!isLoading}
        isLoading={isLoading}
        isEmpty={isEmpty}
        noResultsLabel={<PlaceholderState variant="no-results" />}
        customLoader={<SkeletonList />}
        hasNextPage={!!hasNextPage}
        fetchNextPage={fetchNextPage}
        isFetchingNextPage={isFetchingNextPage}
      >
        <HuList>
          {results.map(item => (
            <ResultRow
              key={item.id}
              result={item}
            />
          ))}
        </HuList>
      </InfiniteList>
      {showNoMoreResultsFooter && <NoMoreResultsFooter />}
    </>
  );
};

export default ResultsView;
