import { useInfiniteQuery } from 'react-query';

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

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';

import { FOLDER_PENDING_ROOT } from 'src/constants/documents';
import {
  DocumentListContainer,
  PendingItem,
} from 'src/pages/dashboard/documents/components/documents';
import { getPendingDocumentList } from 'src/services/documents';
import { getDocumentsList } from 'src/utils/documents';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

const LIMIT = 3;

export const PendingList = () => {
  const {
    data: pendingListData = { pages: [], pageParams: [] },
    isLoading,
    isFetchingNextPage,
    hasNextPage,
    fetchNextPage,
  } = useInfiniteQuery(
    documentsKeys.document.pendingList(FOLDER_PENDING_ROOT),
    ({ pageParam = 1 }) => getPendingDocumentList(pageParam, LIMIT),
    {
      getNextPageParam: (_, pages) => {
        const { page, totalPages } = pages[pages.length - 1]?.data || {};

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

  const pendingList = getDocumentsList(pendingListData);

  const { t } = useLokaliseTranslation(['documents', 'general']);

  return (
    <>
      {isLoading && (
        <HuCardContainer sx={{ width: '100%' }}>
          {Array.from({ length: 3 }, (_, index) => (
            <HuListItem
              key={index}
              loading
            />
          ))}
        </HuCardContainer>
      )}
      {!isLoading && pendingList?.length > 0 && (
        <DocumentListContainer
          title={t('SIGNATURE_PENDING')}
          typographyVariant="globalM"
        >
          <Stack>
            {pendingList?.map((document, index) => (
              <PendingItem
                key={document.id}
                document={document}
                showDivider={index !== pendingList.length - 1 || !!hasNextPage}
              />
            ))}
            {hasNextPage && !isFetchingNextPage && (
              <Button
                onClick={() => fetchNextPage()}
                sx={{
                  width: 'fit-content',
                  alignSelf: 'center',
                  my: 2,
                  mb: 0,
                }}
              >
                {t('general:see_more')}
              </Button>
            )}
          </Stack>
          {isFetchingNextPage && (
            <Stack>
              {Array.from({ length: 3 }, (_, index) => (
                <HuListItem
                  key={index}
                  loading
                />
              ))}
            </Stack>
          )}
        </DocumentListContainer>
      )}
    </>
  );
};

export default PendingList;
