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

import { getPosibleParticipants } from 'src/services/chats';
import { User } from 'src/types/user';

import AcceptCancelDialog from 'src/components/AcceptCancelDialog';
import { useTranslation } from 'src/components/dashboard/chat/ChatThreadInfo/i18n';
import {
  PeopleSearch,
  PeopleSearchProps,
} from 'src/components/dashboard/people/PeopleSearch';
import { peopleSearchKeys } from 'src/components/dashboard/people/queries';

const LIMIT = 50;

export type AddParticipantsDialogProps = Pick<PeopleSearchProps, 'select'> & {
  open: boolean;
  onClose: () => void;
  onAdd: (participants: User[]) => void;
  isLoading?: boolean;
};

const AddParticipantsDialog: FC<AddParticipantsDialogProps> = props => {
  const {
    open,
    onClose,
    onAdd,
    select = (users: User[]) => users,
    isLoading = false,
  } = props;

  const [participants, setParticipants] = useState<User[]>([]);

  const { t } = useTranslation();
  const { id } = useParams();

  const handleAdd = () => {
    onAdd && onAdd(participants);
    handleClose();
  };

  const handleClose = () => {
    onClose && onClose();
    setParticipants([]);
  };

  const handleSelect = (user: User) => {
    const newParticipants = [...participants];

    const index = participants.findIndex(
      participant => participant.id === user.id,
    );

    if (index === -1) {
      newParticipants.push(user);
    } else {
      newParticipants.splice(index, 1);
    }

    setParticipants(newParticipants);
  };

  const handleGetUsers = async (
    search: string,
    page: number = 0,
    limit: number = 100,
  ) => {
    const response = await getPosibleParticipants(id, search, page, limit);

    return response;
  };

  return (
    <AcceptCancelDialog
      open={open}
      title={t('ADD_PARTICIPANTS_COUNT', { count: participants.length })}
      acceptLabel={t('ADD')}
      showCancel
      isLoading={isLoading}
      onAccept={handleAdd}
      onCancel={handleClose}
      onClose={handleClose}
      maxWidth="xs"
      fullWidth
      PaperProps={{
        sx: { maxHeight: '70%' },
      }}
    >
      <PeopleSearch
        queryKey={peopleSearchKeys.searchGroupParticipants}
        onSelect={handleSelect}
        limit={LIMIT}
        select={select}
        multiple
        getUsersList={handleGetUsers}
      />
    </AcceptCancelDialog>
  );
};

export default AddParticipantsDialog;
