import { Image } from '@wix/design-system';
import { media } from '@wix/sdk';
import React, { ReactNode } from 'react';
import { File } from './FileProps';
import { audioIcon, docIcon, videoIcon, defaultIcon, pdfIcon } from './icons';
import { memoize } from 'lodash';

export const THUMB_WIDTH = 48;
export const SMALL_THUMB_WIDTH = 36;
export const resolveFileByMediaType = memoize(
  (
    { mediaType, mediaId }: Pick<File, 'mediaType' | 'mediaId'>,
    showDetails?: boolean,
  ) => {
    let thumbnail: ReactNode;
    let fileUrl: string | undefined;

    switch (mediaType) {
      case 'audio': {
        const audio = media.getAudioUrl(`wix:audio://v1/${mediaId}`);
        fileUrl = audio.url;
        thumbnail = audioIcon;
        break;
      }
      case 'video': {
        const video = media.getVideoUrl(`wix:video://v1/${mediaId}`);
        fileUrl = video.url;
        thumbnail = videoIcon;
        break;
      }
      case 'picture': {
        const image = media.getImageUrl(`wix:image://v1/${mediaId}`);
        const thumbImage = media.getScaledToFillImageUrl(
          image.url,
          THUMB_WIDTH + 20,
          THUMB_WIDTH + 20,
          {},
        );

        fileUrl = image.url;
        thumbnail = (
          <Image
            src={thumbImage}
            style={{
              height: showDetails
                ? `${THUMB_WIDTH}px`
                : `${SMALL_THUMB_WIDTH}px`,
              width: showDetails
                ? `${THUMB_WIDTH}px`
                : `${SMALL_THUMB_WIDTH}px`,
              minHeight: showDetails
                ? `${THUMB_WIDTH}px`
                : `${SMALL_THUMB_WIDTH}px`,
              minWidth: showDetails
                ? `${THUMB_WIDTH}px`
                : `${SMALL_THUMB_WIDTH}px`,
              maxHeight: showDetails
                ? `${THUMB_WIDTH}px`
                : `${SMALL_THUMB_WIDTH}px`,
              maxWidth: showDetails
                ? `${THUMB_WIDTH}px`
                : `${SMALL_THUMB_WIDTH}px`,
            }}
            fit="cover"
            borderRadius={5}
          />
        );
        break;
      }
      case 'document': {
        const document = media.getDocumentUrl(`wix:document://v1/${mediaId}`);
        fileUrl = document.url;
        thumbnail = fileUrl.toLowerCase().endsWith('.pdf') ? pdfIcon : docIcon;
        break;
      }
      default: {
        const document = media.getDocumentUrl(`wix:document://v1/${mediaId}`);
        fileUrl = document.url;
        thumbnail = defaultIcon;
        break;
      }
    }

    return { thumbnail, fileUrl };
  },
);
