import { type FC } from 'react';
import { useMutation } from 'react-query';
import { useNavigate } from 'react-router-dom';

import { IconX } from '@material-hu/icons/tabler';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Divider from '@material-hu/mui/Divider';
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 { removeConversationFromCache } from 'src/pages/dashboard/Conversations/queries';
import { conversationsRoutes } from 'src/pages/dashboard/Conversations/routes';
import { leaveGroup } from 'src/pages/dashboard/Conversations/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

type LeaveGroupProps = {
  title: string;
  userId: number;
  userName: string;
  description: string;
  onClose: () => void;
  channelId: string;
  primaryTextButton?: string;
  secondaryTextButton?: string;
  isLeaveGroup?: boolean;
  canLeaveGroup?: boolean;
};

const LeaveGroup: FC<LeaveGroupProps> = props => {
  const {
    title,
    userId,
    userName,
    onClose,
    description,
    channelId,
    primaryTextButton,
    secondaryTextButton,
    isLeaveGroup = true,
    canLeaveGroup,
  } = props;
  const { t } = useLokaliseTranslation('chat');
  const navigate = useNavigate();
  const { enqueueSnackbar, closeSnackbar: closePreviousSnackbar } =
    useHuSnackbar();
  const leaveGroupGroupMutation = useMutation(() =>
    leaveGroup(channelId, userId.toString()),
  );

  const handleonClick = async () => {
    if (!canLeaveGroup && isLeaveGroup) {
      onClose();
      return;
    }
    closePreviousSnackbar();
    try {
      await leaveGroupGroupMutation.mutateAsync();
      onClose();
      if (!isLeaveGroup) {
        enqueueSnackbar({
          title: t('system_messages.channel_kick_by_user', { user: userName }),
          variant: 'success',
        });
      }
      if (isLeaveGroup) {
        removeConversationFromCache(channelId);
        navigate(conversationsRoutes.conversations());
      }
    } catch {
      enqueueSnackbar({
        title: t('errors.leave_group'),
        variant: 'error',
      });
    }
  };

  return (
    <Stack sx={{ py: 3 }}>
      <Stack sx={{ px: 2 }}>
        <Stack
          sx={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <Typography
            variant="globalS"
            fontWeight="fontWeightSemiBold"
          >
            {title}
          </Typography>
          <IconButton onClick={onClose}>
            <IconX />
          </IconButton>
        </Stack>

        <Typography
          sx={{ my: 3 }}
          variant="globalS"
        >
          {description}
        </Typography>
      </Stack>
      <Divider />
      <Stack
        sx={{
          px: 2,
          flexDirection: 'row',
          mt: 3,
          justifyContent: 'flex-end',
          gap: 2,
        }}
      >
        {leaveGroupGroupMutation.isLoading && <CircularProgress />}
        {secondaryTextButton && (
          <Button
            variant="text"
            disabled={leaveGroupGroupMutation.isLoading}
            onClick={onClose}
          >
            {secondaryTextButton}
          </Button>
        )}
        {primaryTextButton && (
          <Button
            variant="primary"
            disabled={leaveGroupGroupMutation.isLoading}
            onClick={handleonClick}
          >
            {primaryTextButton}
          </Button>
        )}
      </Stack>
    </Stack>
  );
};

export default LeaveGroup;
