import { type FC, Fragment, type RefObject, useEffect } from 'react';
import { type InfiniteQueryObserverBaseResult } from 'react-query';

import { type AxiosResponse } from 'axios';
import Box from '@material-hu/mui/Box';

import { type FormPaginationResponse } from 'src/types/forms';

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

export type FormListProps = InfiniteQueryObserverBaseResult<
  AxiosResponse<FormPaginationResponse>
> & {
  type?: string;
  ListItem: any;
  rootRef?: RefObject<any>;
  noResultsLabel: string;
};

export const FormList: FC<FormListProps> = props => {
  const {
    type,
    ListItem,
    data,
    hasNextPage,
    rootRef,
    noResultsLabel,
    ...listWrapperProps
  } = props;

  useEffect(() => {
    const scrollToTop = () => {
      if (rootRef?.current) {
        rootRef?.current.scrollIntoView();
      }
    };
    scrollToTop();
  }, []);

  const formsPages = data?.pages || [];

  const results = formsPages.flatMap(page => page.data.items);

  const lastPageData = data?.pages[data?.pages.length - 1]?.data;

  return (
    <Box
      sx={{
        backgroundColor: 'background.default',
        px: 2,
        py: 2,
      }}
    >
      <InfiniteList
        totalPages={lastPageData?.totalPages}
        isEmpty={!results.length}
        noResultsLabel={noResultsLabel}
        withEnd
        hasNextPage={hasNextPage}
        sx={{ mt: 1, pb: 1 }}
        {...listWrapperProps}
      >
        {results.map((element, i) => (
          <Fragment key={i}>
            <ListItem {...element} />
          </Fragment>
        ))}
      </InfiniteList>
    </Box>
  );
};

export default FormList;
