import React, { useMemo } from 'react';
import {
  CustomModalLayout,
  Loader,
  Modal,
  Image,
  Box,
} from '@wix/design-system';
import { resolveFileByMediaType } from './resolveFileByMediaType';
import { useDownloadFile } from './useDownloadFile';
import { Download } from '@wix/wix-ui-icons-common';
import { FileViewProps } from './FileProps';
import { useWixPatternsContainer } from '@wix/bex-core/react';

interface FilePreviewModalProps extends FileViewProps {
  isOpen: boolean;
  close: () => void;
  showDetails?: boolean;
}
export const FilePreviewModal = ({
  file,
  isOpen,
  close,
  showDetails,
}: FilePreviewModalProps) => {
  const { translate: t } = useWixPatternsContainer();
  const { downloadFile, isDownloading } = useDownloadFile({ file });
  const { fileUrl } = resolveFileByMediaType(file, showDetails);
  const prefixIcon = useMemo(
    () => (
      <Box verticalAlign="middle">
        {isDownloading ? <Loader size="tiny" /> : <Download size="small" />}
      </Box>
    ),
    [isDownloading],
  );
  return (
    <Modal isOpen={isOpen} onRequestClose={close} shouldCloseOnOverlayClick>
      <CustomModalLayout
        title={file.displayName}
        onCloseButtonClick={close}
        primaryButtonText={t('cairo.customFields.fileUpload.download.cta')}
        primaryButtonProps={{
          prefixIcon,
        }}
        primaryButtonOnClick={downloadFile}
      >
        {file.mediaType === 'video' ? (
          <video
            controls
            style={{
              width: '100%',
              height: 'auto',
              maxHeight: '70vh',
              margin: '0 auto',
            }}
            src={fileUrl}
            autoPlay={false}
          />
        ) : (
          <Image
            style={{ height: '500px', width: '500px', objectFit: 'contain' }}
            src={fileUrl}
          />
        )}
      </CustomModalLayout>
    </Modal>
  );
};
