import { type FC } from 'react';

import { type Attachment, FileTypes } from 'src/types/attachments';
import { type File } from 'src/types/files';

import { useGetDimensionsOfMediaFile } from 'src/components/attachment/hooks/useGetDimensionsOfMediaFile';
import Image from 'src/components/attachment/Image';
import Video from 'src/components/attachment/Video';

const mediaByType = {
  [FileTypes.VIDEO]: ({
    media,
    onLoad,
    mediaHeight,
    mediaWidth,
    defaultMuted,
    grantVideoDownload,
  }: MediaBaseProps) => (
    <Video
      onLoad={onLoad}
      media={media}
      mediaHeight={mediaHeight}
      mediaWidth={mediaWidth}
      defaultMuted={defaultMuted}
      grantDownload={grantVideoDownload}
    />
  ),
  [FileTypes.IMAGE]: ({
    media,
    onLoad,
    onClick,
    hasZoom,
    mediaHeight,
    mediaWidth,
    initialZoom = false,
  }: MediaBaseProps) => (
    <Image
      hasZoom={!!hasZoom}
      media={media}
      onLoad={onLoad}
      onClick={onClick}
      mediaHeight={mediaHeight}
      mediaWidth={mediaWidth}
      initialZoom={initialZoom}
    />
  ),
};

export type MediaBaseProps = {
  media: Partial<Attachment | File>;
  hasZoom?: boolean;
  onLoad?: () => void;
  onClick?: (event: React.MouseEvent<HTMLDivElement>) => void;
  mediaHeight?: number;
  mediaWidth?: number;
  initialZoom?: boolean;
  defaultMuted?: boolean;
  grantVideoDownload?: boolean;
};

const MediaBase: FC<MediaBaseProps> = props => {
  const {
    media: { type },
  } = props;

  const { mediaWidth, mediaHeight } = useGetDimensionsOfMediaFile(props, type);

  return (
    type &&
    mediaByType[type as keyof typeof mediaByType] &&
    mediaByType[type as keyof typeof mediaByType]({
      ...props,
      mediaWidth,
      mediaHeight,
    })
  );
};

export default MediaBase;
