import { type FC } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { IconX } from '@material-hu/icons/tabler';
import CircularProgress from '@material-hu/mui/CircularProgress';
import DialogActions from '@material-hu/mui/DialogActions';
import DialogTitle from '@material-hu/mui/DialogTitle';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { useInviteMembers } from 'src/pages/dashboard/Conversations/hooks/useConversationsQueries';
import { type Member } from 'src/pages/dashboard/Conversations/types';
import { addMembers } from 'src/pages/dashboard/Conversations/stores/membersStore';
import { useLokaliseTranslation } from 'src/utils/i18n';

import SelectMembers from '../../../ConversationsNew/SelectMembers';

type AddMembersProps = {
  title: string;
  onClose: () => void;
  channelId: string;
  membersToExclude: number[];
};

const AddMembers: FC<AddMembersProps> = props => {
  const { title, onClose, channelId, membersToExclude } = props;
  const { t } = useLokaliseTranslation(['chat', 'general']);
  const { mutateAsync, isLoading } = useInviteMembers();
  const { enqueueSnackbar } = useHuSnackbar();

  const form = useForm({
    defaultValues: {
      filter: '',
      users: [],
    },
  });

  const { watch } = form;

  const { users } = watch();

  const submit = async (values: { users: Member[]; filter: string }) => {
    try {
      await mutateAsync({
        channelId,
        users: values.users.map(user => user.id.toString()),
      });
      addMembers(values.users);
      onClose();
    } catch {
      enqueueSnackbar({
        title: t('chat:errors.invite_members'),
        variant: 'error',
      });
    }
  };

  return (
    <>
      <DialogTitle>
        <Stack
          sx={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <Typography
            variant="globalS"
            fontWeight="fontWeightSemiBold"
          >
            {title}
          </Typography>
          <IconButton onClick={onClose}>
            <IconX />
          </IconButton>
        </Stack>
        <Typography variant="globalXS">
          {t('chat:groups.create.select_members', { count: users.length })}
        </Typography>
      </DialogTitle>
      <Stack sx={{ flex: 1, overflow: 'auto' }}>
        <FormProvider {...form}>
          <SelectMembers
            withoutContainer
            membersToExclude={membersToExclude}
          />
        </FormProvider>
      </Stack>
      <DialogActions
        sx={{
          padding: 3,
        }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            mt: 3,
            gap: 1,
            justifyContent: 'flex-end',
          }}
        >
          {isLoading && <CircularProgress />}
          <Button
            variant="primary"
            disabled={isLoading || !users.length}
            onClick={form.handleSubmit(submit)}
          >
            {t('general:add')}
          </Button>
        </Stack>
      </DialogActions>
    </>
  );
};

export default AddMembers;
