import { memo, useEffect } from 'react';
import { useInfiniteQuery } from 'react-query';

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

import { type GetViewersFunction } from 'src/hooks/usePostViewers';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';
import { getInitials } from 'src/utils/userUtils';

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

import ViewersListSkeleton from './ViewersListSkeleton';

const VIEWERS_PAGE_SIZE = 25;

type ViewersListProps = {
  postId: number;
  getViewers: GetViewersFunction;
  searchQuery?: string;
  onViewerCountUpdate?: (count: number) => void;
};

const ViewersList = ({
  postId,
  getViewers,
  searchQuery = '',
  onViewerCountUpdate,
}: ViewersListProps) => {
  const { t } = useTranslation();

  const {
    data,
    isLoading,
    fetchNextPage,
    isFetchingNextPage,
    hasNextPage,
    isSuccess,
  } = useInfiniteQuery(
    ['post-viewers-list', postId, searchQuery],
    ({ pageParam }) => {
      return getViewers({
        limit: VIEWERS_PAGE_SIZE,
        cursor: pageParam,
        search: searchQuery,
      });
    },
    {
      enabled: !!postId,
      getNextPageParam: lastPage => lastPage.data.cursor ?? undefined,
    },
  );

  const viewers = data?.pages.flatMap(response => response.data.items || []);

  useEffect(() => {
    if (!hasNextPage && data && !searchQuery && onViewerCountUpdate) {
      const viewerCount = data.pages.flatMap(
        response => response.data.items || [],
      ).length;
      onViewerCountUpdate(viewerCount);
    }
  }, [hasNextPage, data, searchQuery, onViewerCountUpdate]);

  return (
    <CardContainer fullWidth>
      <InfiniteList
        isLoading={isLoading}
        fetchNextPage={fetchNextPage}
        isFetchingNextPage={isFetchingNextPage}
        totalPages={data?.pages.length}
        isSuccess={isSuccess}
        isEmpty={!viewers?.length}
        hasNextPage={hasNextPage}
        customLoader={<ViewersListSkeleton />}
      >
        {viewers?.map(item => {
          const { viewer } = item;
          const fullName = [viewer.firstName, viewer.lastName]
            .filter(Boolean)
            .join(' ');
          return (
            <div key={viewer.id}>
              <HuListItem
                sx={{
                  borderBottom: '1px solid',
                  borderColor: 'divider',
                  pt: 1,
                  pb: 2,
                  mb: 1,
                }}
                slotProps={{
                  container: {
                    sx: { pl: 0, py: 0 },
                  },
                }}
                avatar={{
                  src: viewer.profilePicture ?? undefined,
                  text: getInitials(fullName),
                  alt: fullName,
                }}
                text={{ title: fullName }}
                sideContent={
                  viewer.isExternal && (
                    <Pills
                      label={t('group:external')}
                      type="neutral"
                      size="small"
                      hasIcon={false}
                    />
                  )
                }
              />
            </div>
          );
        })}
      </InfiniteList>
    </CardContainer>
  );
};

export default memo(ViewersList);
