import { type FC } from 'react';
import { useFormContext } from 'react-hook-form';

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

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

import { useAuth } from 'src/contexts/JWTContext';
import { type Member } from 'src/pages/dashboard/Conversations/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useGetUserList } from '../../hooks/useConversationsQueries';

import ShowSelectedMembers from './ShowSelectedMembers';
import UsersList from './UsersList';

type SelectMembersProps = {
  membersToExclude?: number[];
  withoutContainer?: boolean;
};

const SelectMembers: FC<SelectMembersProps> = props => {
  const { membersToExclude, withoutContainer } = props;
  const { t } = useLokaliseTranslation(['chat', 'general']);
  const { setValue, watch } = useFormContext();
  const { user } = useAuth();

  const filter = watch('filter');
  const users = watch('users') as Member[];

  const { members, hasNextPage, ...listWrapperProps } = useGetUserList({
    query: filter,
    userId: user?.id,
  });

  const handleSelectMember = (member: Member) => {
    if (membersToExclude?.includes(member.id)) {
      return;
    }
    if (users.some(elem => elem.id === member.id)) {
      const newArray = users.filter(elem => elem.id !== member.id);
      setValue('users', newArray);
    } else {
      setValue('users', [...users, member]);
    }
  };

  return (
    <>
      <HuFormInputClassic
        inputProps={{
          maxLength: 20,
          placeholder: t('general:search'),
          hasCounter: false,
          sx: {
            px: 2,
            mb: 2,
          },
          startAdornment: <IconSearch />,
        }}
        name="filter"
      />
      {!!users.length && <ShowSelectedMembers />}
      <Stack sx={{ flex: 1, overflow: 'auto' }}>
        <UsersList
          withCheckbox
          withoutContainer={withoutContainer}
          selectedMembers={users}
          members={members}
          hasNextPage={hasNextPage || false}
          listWrapperProps={listWrapperProps}
          onSelectMember={handleSelectMember}
          membersToExclude={membersToExclude}
        />
      </Stack>
    </>
  );
};

export default SelectMembers;
