import { useState, FC } from 'react';
import { useInfiniteQuery } from 'react-query';
import { useParams } from 'react-router-dom';

import { useDebounce } from '@material-hu/hooks/useDebounce';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuSearch from '@material-hu/components/design-system/Inputs/Search';

import useGeneralError from 'src/hooks/useGeneralError';
import { CALL_SNACKBAR_BOTTOM_SPACING } from 'src/pages/dashboard/videoCall/constants';
import { videoCallKeys } from 'src/pages/dashboard/videoCall/queries';
import { getInstanceParticipants } from 'src/services/streaming';
import { Participant } from 'src/types/stream';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getNextCursor } from 'src/utils/pagination';

import AddParticipantUserList from './AddParticipantList';
import SelectedParticipants from './SelectedParticipants';

type AddParticipantProps = {
  selectedParticipants: Participant[];
  setSelectedParticipants: (participants: Participant[]) => void;
  disabledSelectMoreParticipant: boolean;
  maxParticipantsToAdd: number;
};

const AddParticipant: FC<AddParticipantProps> = ({
  selectedParticipants,
  setSelectedParticipants,
  disabledSelectMoreParticipant,
  maxParticipantsToAdd,
}) => {
  const [query, setQuery] = useState<string>('');
  const { callId } = useParams();
  const { t } = useLokaliseTranslation('calls');
  const debouncedQuery = useDebounce(query);
  const showGeneralError = useGeneralError();

  const participantsData = useInfiniteQuery(
    videoCallKeys.instanceParticipants(debouncedQuery),
    ({ pageParam = '' }) => {
      return getInstanceParticipants({
        id: callId,
        q: debouncedQuery,
        limit: 10,
        cursor: pageParam,
      });
    },
    {
      getNextPageParam: getNextCursor,
      onError: err =>
        showGeneralError(err, t('ERROR_GET_LIST_USERS'), true, {
          spacing: {
            bottom: CALL_SNACKBAR_BOTTOM_SPACING,
          },
        }),
    },
  );

  const participants = participantsData?.data
    ? participantsData.data?.pages.flatMap(page => page.data.items)
    : [];

  const handleChangeQuery = (value: string) => setQuery(value);

  const handleSelectParticipant = (participant: Participant) => {
    if (selectedParticipants.some(elem => elem.id === participant.id)) {
      const newArray = selectedParticipants.filter(
        elem => elem.id !== participant.id,
      );
      setSelectedParticipants(newArray);
    } else {
      setSelectedParticipants([...selectedParticipants, participant]);
    }
  };

  return (
    <Stack sx={{ height: '100%' }}>
      <Stack>
        <HuSearch
          variant="custom"
          onChange={handleChangeQuery}
          value={query}
          sx={{ mb: 2 }}
        />
        <Typography
          variant="globalXXS"
          color="text.neutralText"
          sx={{
            mb: selectedParticipants.length ? 1.5 : 2,
          }}
        >
          {t('MAX_PARTICIPANTS', {
            count: selectedParticipants.length,
            max: maxParticipantsToAdd,
          })}
        </Typography>
        {selectedParticipants.length > 0 && (
          <SelectedParticipants
            selectedParticipants={selectedParticipants}
            setSelectedParticipants={setSelectedParticipants}
          />
        )}
      </Stack>

      <AddParticipantUserList
        selectedParticipants={selectedParticipants}
        participants={participants}
        listWrapperProps={{
          fetchNextPage: participantsData?.fetchNextPage,
          isFetchingNextPage: participantsData?.isFetchingNextPage,
          isLoading: participantsData?.isLoading,
          hasNextPage: participantsData?.hasNextPage,
          isSuccess: participantsData?.isSuccess,
          isEmpty: participantsData?.isSuccess && !participants?.length,
          showNoResultsMessage: false,
        }}
        onSelectParticipant={handleSelectParticipant}
        disabledSelectMoreParticipant={disabledSelectMoreParticipant}
      />
    </Stack>
  );
};

export default AddParticipant;
