import { FC, memo, useEffect } from 'react';
import { useQuery } from 'react-query';

import { Gif } from '@giphy/react-components';

import { IconAlertCircle } from '@material-hu/icons/tabler';
import { Typography, useTheme } from '@material-hu/mui/index';
import Stack from '@material-hu/mui/Stack';

import { getGif } from 'src/services/attachments';

import { useLokaliseTranslation } from 'src/utils/i18n';
import { attachmentKeys } from 'src/components/attachment/queries';

import ControlledGif from './ControlledGif';

export type MediaBaseProps = {
  media: {
    image_height?: number;
    image_width?: number;
    externalReference?: {
      id?: string;
    };
    external_reference?: {
      id?: string;
    };
  };
  withLimitDuration?: boolean;
  width?: number;
  duration?: number;
  onError?: () => void;
};

const GifDisplay: FC<MediaBaseProps> = ({
  media,
  withLimitDuration = false,
  width = 200,
  duration = 30000,
  onError,
}) => {
  const theme = useTheme();
  const { t } = useLokaliseTranslation('chat');
  const gifId =
    media?.externalReference?.id || media?.external_reference?.id || '';
  const displayHeight =
    media?.image_width && media?.image_height
      ? Math.round((width * media.image_height) / media.image_width)
      : undefined;

  const {
    data: gif,
    isError,
    isLoading,
  } = useQuery(attachmentKeys.gif(gifId), () => getGif(gifId), {
    enabled: !!gifId,
  });

  useEffect(() => {
    if (isError) {
      onError?.();
    }
  }, [isError, onError]);

  if (isLoading) {
    return (
      <Stack
        sx={{
          width,
          height: displayHeight ?? width,
        }}
      />
    );
  }

  if (!gif || isError) {
    return (
      <Stack
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          gap: 0.5,
        }}
      >
        <IconAlertCircle
          color={theme.palette.new.text.neutral.lighter}
          size={18}
        />
        <Typography
          variant="globalS"
          sx={{ whiteSpace: 'pre-wrap' }}
          fontStyle="italic"
        >
          {t('messages.block_not_available')}
        </Typography>
      </Stack>
    );
  }

  if (withLimitDuration) {
    return (
      <ControlledGif
        gif={gif}
        duration={duration}
        width={width}
        height={displayHeight}
      />
    );
  }

  return (
    <Gif
      noLink
      hideAttribution
      gif={gif?.data}
      borderRadius={8}
      width={width}
    />
  );
};

export default memo(GifDisplay);
