import { FC, useState } from 'react';
import { FormProvider, useFormContext } from 'react-hook-form';

import Checkbox from '@material-hu/mui/Checkbox';
import FormControlLabel from '@material-hu/mui/FormControlLabel';
import Stack from '@material-hu/mui/Stack';

import Search from '@material-hu/components/design-system/Inputs/Search';
import useInfiniteUsersPublicSearch from 'src/hooks/useInfiniteUsersPublicSearch';
import { User } from 'src/types/user';
import { addOrRemoveById } from 'src/utils/arrays';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

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

import { NoResultsLabel } from 'src/components/NoResultsLabel';

import SelectMembersListItem from './SelectMembersListItem';

type Props = {
  previousUserIds: number[];
};

const SelectMembers: FC<Props> = props => {
  const { previousUserIds } = props;
  const [search, setSearch] = useState<string>('');

  const { t } = useTranslation(['group']);

  const form = useFormContext<{ selectedItems: User[] }>();

  const { watch } = form;
  const { selectedItems } = watch();

  const allUsers = useInfiniteUsersPublicSearch(
    {
      search,
      notIncludingIds: previousUserIds,
    },
    { keepPreviousData: false },
  );

  return (
    <Stack sx={{ height: '100%' }}>
      <Stack
        sx={{
          flex: 1,
          overflow: 'auto',
          width: '100%',
        }}
      >
        <Stack
          sx={{
            mb: 2,
          }}
        >
          <Search
            value={search}
            placeholder={t('general:search')}
            onChange={setSearch}
          />
        </Stack>
        <FormProvider {...form}>
          <Stack sx={{ flex: 1, overflow: 'auto' }}>
            <InfiniteList
              isSuccess={allUsers.isSuccess}
              isLoading={allUsers.isLoading}
              isEmpty={
                allUsers.data?.pages && !allUsers.data?.pages[0]?.data?.count
              }
              fetchNextPage={allUsers.fetchNextPage}
              hasNextPage={allUsers.hasNextPage}
              isFetchingNextPage={allUsers.isFetchingNextPage}
              noResultsLabel={<NoResultsLabel />}
            >
              {allUsers.data?.pages
                .flatMap(page => page.data.items)
                .map(user => (
                  <Stack
                    key={user.id}
                    sx={{ flexDirection: 'row', alignItems: 'center', mb: 2 }}
                  >
                    <FormControlLabel
                      control={
                        <Checkbox
                          onClick={() =>
                            form.setValue(
                              'selectedItems',
                              addOrRemoveById(selectedItems, user),
                            )
                          }
                          checked={selectedItems
                            .map(item => item.id)
                            .includes(user.id)}
                        />
                      }
                      label={<SelectMembersListItem user={user} />}
                    />
                  </Stack>
                ))}
            </InfiniteList>
          </Stack>
        </FormProvider>
      </Stack>
    </Stack>
  );
};

export default SelectMembers;
