import { FC, memo } from 'react';

import CancelIcon from '@material-hu/icons/material/Cancel';
import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Container from '@material-hu/mui/Container';
import IconButton from '@material-hu/mui/IconButton';
import Tooltip from '@material-hu/mui/Tooltip';

import PostPreviewLink from 'src/pages/dashboard/feed/components/PostPreviewLink';
import { LinkPreviewResponse } from 'src/types/previewLink';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';
import { getMetadata } from 'src/utils/previewLink';

export type PreviewLinkCardProps = {
  linkPreviews: Record<string, LinkPreviewResponse>;
  isLoading: boolean;
  onRemove: () => void;
};

const PreviewLinkCard: FC<PreviewLinkCardProps> = props => {
  const { linkPreviews, isLoading, onRemove } = props;

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

  if (!linkPreviews && !isLoading) return null;

  const metadata = getMetadata(linkPreviews);

  return (
    <Container sx={{ p: '0 !important', mt: 1, position: 'relative' }}>
      <PostPreviewLink linkPreviews={linkPreviews} />
      {isLoading && (
        <Box sx={{ textAlign: 'center' }}>
          <CircularProgress />
        </Box>
      )}
      {!!metadata && !isLoading && (
        <Tooltip
          title={t('post:remove_preview_link')}
          placement="top"
        >
          <IconButton
            sx={{
              position: 'absolute',
              top: '-2px',
              right: '-2px',
              '& svg': {
                backgroundColor: 'white',
                borderRadius: '50%',
              },
            }}
            onClick={onRemove}
          >
            <CancelIcon />
          </IconButton>
        </Tooltip>
      )}
    </Container>
  );
};

export default memo(PreviewLinkCard);
