import { FC } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useInfiniteQuery } from 'react-query';

import { useDebounce } from '@material-hu/hooks/useDebounce';
import { IconSearch, IconUser } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import HuFormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';

import { getEventInvitationSelection } from 'src/services/events';
import { Event } from 'src/types/events';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getListItemsLength, getNextPage } from 'src/utils/pagination';
import { getFullName } from 'src/utils/userUtils';

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

import { eventsKeys } from '../queries';
import { formatInvitation } from '../utils';

import EmptyState from './EmptyState';

type Props = {
  event: Event;
  onClose: Function;
  selection: object;
};

export const SelectedPeople: FC<Props> = ({ event, selection }) => {
  const { t } = useLokaliseTranslation('events');

  const form = useForm({ defaultValues: { search: '' } });
  const debouncedSearch = useDebounce(form.watch('search'));

  const allUsers = useInfiniteQuery(
    eventsKeys.eventUsersSelected(event.id, {
      debouncedSearch,
      ...selection,
    }),
    ({ pageParam = 1 }) =>
      getEventInvitationSelection(
        event.id,
        debouncedSearch,
        formatInvitation(selection),
        pageParam,
      ),
    {
      getNextPageParam: (lastPage, pages) =>
        getNextPage(getListItemsLength(pages), 100, pages),
    },
  );

  const isEmpty = allUsers.data?.pages && !allUsers.data?.pages[0]?.data?.count;

  return (
    <FormProvider {...form}>
      <Stack
        sx={{
          gap: 3,
        }}
      >
        <HuFormInputClassic
          name="search"
          inputProps={{
            placeholder: t('SEARCH_PEOPLE'),
            startAdornment: <IconSearch size={24} />,
            hasCounter: false,
          }}
        />
        {isEmpty && (
          <EmptyState
            sx={{ border: 'none', mt: 2 }}
            titleProps={{
              title: t('NO_ONE_HERE'),
              description: t('NO_ONE_HERE_DESCRIPTION'),
            }}
          />
        )}
        <InfiniteList
          isSuccess={!!allUsers.data}
          isLoading={allUsers.isLoading}
          isEmpty={isEmpty}
          fetchNextPage={allUsers.fetchNextPage}
          hasNextPage={allUsers.hasNextPage}
          isFetchingNextPage={allUsers.isFetchingNextPage}
          showNoResultsMessage={false}
        >
          {allUsers.data?.pages
            .flatMap(page => page.data.items)
            .map(user => {
              return (
                <HuListItem
                  key={user.id}
                  avatar={{ src: user.profilePicture, Icon: IconUser }}
                  text={{ title: getFullName(user) }}
                />
              );
            })}
        </InfiniteList>
      </Stack>
    </FormProvider>
  );
};
