import { useInfiniteQuery } from 'react-query';

import Stack from '@material-hu/mui/Stack';

import { IconZoomExclamation } from '@material-hu/icons/tabler';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';
import StateCard from '@material-hu/components/composed-components/StateCard';

import {
  DocumentListContainer,
  FolderItem,
} from 'src/pages/dashboard/documents/components/documents';
import { getFolderList } from 'src/services/documents';
import { getDocumentsList } from 'src/utils/documents';
import { useLokaliseTranslation } from 'src/utils/i18n';

import InfiniteList from 'src/components/list/InfiniteList';

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

const LIMIT = 10;

export const FolderList = () => {
  const { t } = useLokaliseTranslation('documents');

  const {
    data = { pages: [], pageParams: [] },
    isLoading,
    isSuccess,
    isFetchingNextPage,
    hasNextPage,
    fetchNextPage,
  } = useInfiniteQuery(
    documentsKeys.folder.list(),
    ({ pageParam = 1 }) => getFolderList(pageParam, LIMIT),
    {
      getNextPageParam: (_, pages) => {
        const { page, totalPages } = pages[pages.length - 1]?.data || {};

        return page < totalPages ? pages.length + 1 : undefined;
      },
    },
  );

  const folderList = getDocumentsList(data);

  return (
    <DocumentListContainer
      title={t('FOLDERS')}
      typographyVariant="globalM"
    >
      <InfiniteList
        isSuccess={isSuccess}
        isLoading={isLoading}
        isEmpty={data?.pages.length === 0}
        noResultsLabel={t('EMPTY_FOLDER_LIST')}
        isFetchingNextPage={isFetchingNextPage}
        fetchNextPage={fetchNextPage}
        hasNextPage={hasNextPage}
        showNoResultsMessage={false}
        loadingSkeleton={isLoading}
        renderSkeleton={
          <Stack sx={{ py: 1 }}>
            <HuListItem loading />
            <HuListItem loading />
            <HuListItem loading />
          </Stack>
        }
      >
        {folderList?.length === 0 && (
          <StateCard
            sx={{ p: 3, border: 'none' }}
            slotProps={{
              title: {
                title: t('empty_folder_list'),
                description: t('empty_folder'),
              },
              avatar: {
                Icon: IconZoomExclamation,
              },
            }}
          />
        )}

        {folderList?.map((folder, index) => (
          <FolderItem
            key={folder.id}
            folder={folder}
            showDivider={index !== folderList.length - 1 || !!hasNextPage}
          />
        ))}
      </InfiniteList>
    </DocumentListContainer>
  );
};

export default FolderList;
