import React, { ReactNode } from 'react';
import {
  IVideoContent,
  MATRIX_SPOILER_PROPERTY_NAME,
  MATRIX_SPOILER_REASON_PROPERTY_NAME,
} from '../../../../types/matrix/common';
import { getBlobSafeMimeType } from '../../../utils/mimeTypes';
import { RenderVideoContentProps } from '../MsgTypeRenderers';
import { StreamMediaShell } from './StreamMediaShell';

export type StreamMediaVideoProps = {
  content: IVideoContent;
  own: boolean;
  renderAsFile: () => ReactNode;
  renderVideoContent: (props: RenderVideoContentProps) => ReactNode;
};

export function StreamMediaVideo({
  content,
  own,
  renderAsFile,
  renderVideoContent,
}: StreamMediaVideoProps) {
  const videoInfo = content.info;
  const mxcUrl = content.file?.url ?? content.url;
  const safeMimeType = getBlobSafeMimeType(videoInfo?.mimetype ?? '');

  // Mirror MVideo's fallback: if mime / info is bad but we have a URL,
  // render as a file attachment. Pin-menu / search go through the legacy
  // MVideo path entirely.
  if (!videoInfo || !safeMimeType.startsWith('video') || typeof mxcUrl !== 'string') {
    if (mxcUrl) return <>{renderAsFile()}</>;
    return null;
  }

  return (
    <StreamMediaShell naturalW={videoInfo.w} naturalH={videoInfo.h} own={own}>
      {renderVideoContent({
        body: content.body || 'Video',
        info: videoInfo,
        mimeType: safeMimeType,
        url: mxcUrl,
        encInfo: content.file,
        markedAsSpoiler: content[MATRIX_SPOILER_PROPERTY_NAME],
        spoilerReason: content[MATRIX_SPOILER_REASON_PROPERTY_NAME],
      })}
    </StreamMediaShell>
  );
}
