import React, { ReactNode } from 'react';
import {
  IImageContent,
  MATRIX_SPOILER_PROPERTY_NAME,
  MATRIX_SPOILER_REASON_PROPERTY_NAME,
} from '../../../../types/matrix/common';
import { RenderImageContentProps } from '../MsgTypeRenderers';
import { StreamMediaShell } from './StreamMediaShell';

// Filename-shaped bodies (`IMG_20240501_140532.jpg`, `Screenshot_*`, plain
// extensions) are useless as alt-text — bridged photos from
// mautrix-telegram set body to the source filename. Treat those as
// decorative; users with a real caption keep theirs.
const FILENAME_ALT_RE =
  /^(image|img[_-].*|screenshot[_-].*|.+\.(?:jpe?g|png|webp|gif|bmp|svg|heic|avif|tiff?))$/i;
const altFor = (body?: string): string => (body && !FILENAME_ALT_RE.test(body) ? body : '');

export type StreamMediaImageProps = {
  content: IImageContent;
  own: boolean;
  renderImageContent: (props: RenderImageContentProps) => ReactNode;
};

export function StreamMediaImage({ content, own, renderImageContent }: StreamMediaImageProps) {
  const imgInfo = content.info;
  const mxcUrl = content.file?.url ?? content.url;
  if (typeof mxcUrl !== 'string') return null;

  return (
    <StreamMediaShell naturalW={imgInfo?.w} naturalH={imgInfo?.h} own={own}>
      {renderImageContent({
        body: altFor(content.body),
        info: imgInfo,
        mimeType: imgInfo?.mimetype,
        url: mxcUrl,
        encInfo: content.file,
        markedAsSpoiler: content[MATRIX_SPOILER_PROPERTY_NAME],
        spoilerReason: content[MATRIX_SPOILER_REASON_PROPERTY_NAME],
      })}
    </StreamMediaShell>
  );
}
