import { FC } from 'react';
import { useInfiniteQuery } from 'react-query';

import { useDebounce } from '@material-hu/hooks/useDebounce';
import List from '@material-hu/mui/List';
import ListSubheader from '@material-hu/mui/ListSubheader';

import useGeneralError from 'src/hooks/useGeneralError';
import useRequiredParams from 'src/hooks/useRequiredParams';
import { getGroupMembers } from 'src/services/groups';
import { GroupMember } from 'src/types/groups';
import { User, UserDictionaryItem } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getUsersForSectionList } from 'src/utils/userUtils';

import PeopleItem from 'src/components/dashboard/people/PeopleItem';
import InfiniteList from 'src/components/list/InfiniteList';

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

export type GroupPeopleListProps = {
  select?: (users: User[]) => User[];
  query?: string;
  handleSelect?: (users: User) => void;
};

export const GroupPeopleList: FC<GroupPeopleListProps> = props => {
  const { select = (users: User[]) => users, query, handleSelect } = props;

  const { t } = useLokaliseTranslation('group');
  const showGeneralError = useGeneralError();
  const debouncedQuery = useDebounce(query);
  const { id: groupId } = useRequiredParams(['id']);

  const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } =
    useInfiniteQuery(
      groupsKeys.searchMember(groupId, debouncedQuery || ''),
      ({ pageParam = '' }) =>
        getGroupMembers(groupId, pageParam, debouncedQuery || ''),
      {
        getNextPageParam: lastPage => lastPage?.data?.cursor,
        onError: () => {
          showGeneralError(t('general:error_loading_members'));
        },
      },
    );

  const results =
    data?.pages.reduce(
      (resultsAcc: UserDictionaryItem[], page) =>
        getUsersForSectionList(
          select(page.data.items.map((member: GroupMember) => member.user)),
          resultsAcc,
        ),
      [],
    ) || [];

  return (
    <InfiniteList
      isSuccess={!!results}
      isLoading={isLoading}
      isEmpty={results?.length === 0}
      fetchNextPage={fetchNextPage}
      hasNextPage={hasNextPage}
      isFetchingNextPage={isFetchingNextPage}
      sx={{
        position: 'relative',
        zIndex: 2,
        overflow: 'auto',
        height: '300px',
        backgroundColor: '#f4f5f7',
      }}
    >
      <List subheader={<li />}>
        {results.map((item: UserDictionaryItem) => (
          <li key={`section-${item.character}`}>
            <ul>
              <ListSubheader
                style={{
                  top: '-2px',
                  backgroundColor: '#f4f5f7',
                }}
              >
                {item.character}
              </ListSubheader>
              {item.users.map((user: User) => (
                <PeopleItem
                  user={user}
                  key={`user-${user.id}`}
                  onSelect={handleSelect}
                />
              ))}
            </ul>
          </li>
        ))}
      </List>
    </InfiniteList>
  );
};

export default GroupPeopleList;
