import { useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useInfiniteQuery } from 'react-query';

import UserAvatar from '@composed-components/UserAvatar';
import CardContainer from '@design-system/CardContainer';
import Search from '@design-system/Inputs/Search';
import ListItemSkeleton from '@design-system/List/components/ListItemSkeleton';
import StateCard from '@design-system/StateCard';
import { useDebounce } from '@hooks/useDebounce';
import useVirtualizer from '@hooks/useVirtualizer';
import { CircularProgress, Stack, Typography } from '@mui/material';
import { IconZoomExclamation } from '@tabler/icons-react';

import { type SelectedCollaboratorsDrawerContentProps } from './types';

const ROW_HEIGHT = 64;

const SelectedCollaboratorsDrawerContent = ({
  totalCount,
  service,
  queryKey,
}: SelectedCollaboratorsDrawerContentProps) => {
  const { t } = useTranslation('material_hu_only');
  const [search, setSearch] = useState('');
  const debouncedSearch = useDebounce(search);
  const scrollElementRef = useRef<HTMLDivElement | null>(null);

  const { data, isLoading, fetchNextPage, isFetchingNextPage, hasNextPage } =
    useInfiniteQuery(
      [queryKey, debouncedSearch],
      ({ pageParam }) =>
        service({
          q: debouncedSearch || undefined,
          limit: 10,
          cursor: pageParam,
        }),
      {
        getNextPageParam: lastPage => {
          if (lastPage.data.cursor) {
            return lastPage.data.cursor;
          }
          return undefined;
        },
      },
    );

  const results = data?.pages.flatMap(page => page.data.items || []) ?? [];

  const { virtualRows, rowVirtualizer } = useVirtualizer({
    scrollElementRef,
    registers: results,
    virtualizerOptions: {
      estimateSize: () => ROW_HEIGHT,
      count: results.length,
      getScrollElement: () => scrollElementRef.current,
      overscan: 5,
    },
    hasNextPage,
    isFetchingNextPage,
    fetchNextPage,
  });

  const count = results.length;
  const isEmpty = !isLoading && !count;
  const showList = !isLoading && count > 0;

  return (
    <CardContainer
      fullWidth
      color="grey"
      sx={{
        height: '100%',
        boxSizing: 'border-box',
        '& .MuiCardContent-root': { height: '100%', boxSizing: 'border-box' },
      }}
    >
      <Stack sx={{ flex: 1, gap: 2, height: '100%' }}>
        <Search
          value={search}
          onChange={setSearch}
        />
        {isLoading && (
          <Stack>
            {Array.from({ length: 5 }).map((_, i) => (
              <ListItemSkeleton key={i} />
            ))}
          </Stack>
        )}
        {isEmpty && (
          <StateCard
            title={t('audience.no_collaborators_match_title')}
            description={t('audience.no_collaborators_match_description')}
            icon={IconZoomExclamation}
            slotProps={{
              card: { sx: { border: 'none' } },
            }}
          />
        )}
        {showList && (
          <>
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
            >
              {t('audience.total_collaborators', { count: totalCount })}
            </Typography>
            <Stack
              ref={scrollElementRef}
              sx={{ flex: 1, overflow: 'auto' }}
            >
              <Stack
                sx={{
                  height: `${rowVirtualizer.getTotalSize()}px`,
                  position: 'relative',
                  width: '100%',
                }}
              >
                {virtualRows.map(virtualItem => {
                  const user = results[virtualItem.index];
                  return (
                    <Stack
                      key={user.id}
                      sx={{
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        width: '100%',
                        transform: `translateY(${virtualItem.start}px)`,
                      }}
                    >
                      <UserAvatar
                        user={user}
                        profileProps={{ showEmployeeInternalId: true }}
                      />
                    </Stack>
                  );
                })}
              </Stack>
              {isFetchingNextPage && (
                <Stack
                  sx={{
                    justifyContent: 'center',
                    alignItems: 'center',
                    py: 2,
                  }}
                >
                  <CircularProgress size={20} />
                </Stack>
              )}
            </Stack>
          </>
        )}
      </Stack>
    </CardContainer>
  );
};

export default SelectedCollaboratorsDrawerContent;
