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

import { IconX } from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuAvatar from '@material-hu/components/design-system/Avatar';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

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

import { useUploadImage } from '../../hooks/useConversationsQueries';
import FormGroupInfo from '../shared/FormGroupInfo';

const SelectGroupInfo: FC = () => {
  const theme = useTheme();
  const { watch, setValue } = useFormContext();
  const { t } = useLokaliseTranslation('chat');
  const { user } = useAuth();
  const { enqueueSnackbar } = useHuSnackbar();

  const uploadImgGroupMutation = useUploadImage();

  const handleChange = async (event: any) => {
    try {
      const file = event.target.files[0];

      const dataImage = await uploadImgGroupMutation.mutateAsync(file);

      setValue('picture', formateDataImage(dataImage));
    } catch (error) {
      enqueueSnackbar({
        title: t('errors.upload_image'),
        variant: 'error',
      });
    }
  };

  const { users, picture } = watch();

  const handleDeleteMember = (member: Member) => {
    const newArray = users.filter((elem: Member) => elem.id !== member.id);
    setValue('users', [...newArray]);
  };

  return (
    <Stack
      sx={{
        flex: 1,
        overflow: 'auto',
        alignItems: 'center',
        position: 'relative',
      }}
    >
      <FormGroupInfo
        name="name"
        picture={picture?.image_url}
        isLoading={uploadImgGroupMutation.isLoading}
        onChange={handleChange}
      />
      <Stack sx={{ mt: 4 }}>
        <Typography
          variant="globalS"
          fontWeight="fontWeightSemiBold"
          sx={{ textAlign: 'start' }}
        >
          {t('groups.members', { count: users.length + 1 })}
        </Typography>
        <HuCardContainer
          sx={{ mt: 2, mb: 2, '& .MuiCardContent-root': { p: 0 } }}
        >
          <Stack
            sx={{
              my: 2,
              flexDirection: 'row',
              px: 2,
              width: '100%',
              gap: 1,
              alignItems: 'center',
            }}
          >
            <HuAvatar
              src={user?.profilePicture ?? ''}
              text={getInitials(`${user?.firstName} ${user?.lastName}`)}
            />
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
            >
              {t('you')}
            </Typography>
          </Stack>
          {users.length >= 1 && <Divider sx={{ mx: 2 }} />}
          {!!users.length &&
            users.map((elem: Member, index: number) => (
              <Fragment key={elem.id}>
                <Stack
                  sx={{
                    my: 2,
                    flexDirection: 'row',
                    px: 2,
                    width: '100%',
                    justifyContent: 'space-between',
                  }}
                >
                  <Stack
                    sx={{
                      flexDirection: 'row',
                      gap: 1,
                      alignItems: 'center',
                    }}
                  >
                    <HuAvatar
                      src={elem.picture_url}
                      text={getInitials(`${elem.first_name} ${elem.last_name}`)}
                    />
                    <Typography
                      variant="globalS"
                      fontWeight="fontWeightSemiBold"
                    >
                      {`${elem.first_name} ${elem.last_name}`}
                    </Typography>
                  </Stack>
                  <IconButton onClick={() => handleDeleteMember(elem)}>
                    <IconX color={theme.palette.new.text.neutral.default} />
                  </IconButton>
                </Stack>
                {index !== users.length - 1 && <Divider sx={{ mx: 2 }} />}
              </Fragment>
            ))}
        </HuCardContainer>
      </Stack>
    </Stack>
  );
};

export default SelectGroupInfo;
