import React, { useState } from 'react';
import { Box, TableListItem } from '@wix/design-system';
import { FileViewProps } from './FileProps';
import { useDownloadFile } from './useDownloadFile';
import { FilePreviewModal } from './FilePreviewModal';
import { FileCard } from './FileCard';

export function FilePreview({
  file,
  showDownloadCTA,
  showDetails,
}: FileViewProps) {
  const { mediaType } = file;
  const [isPreviewOpen, setIsPreviewOpen] = useState(false);
  const { downloadFile } = useDownloadFile({ file });
  const supportedPreviewTypes = ['picture', 'video'];

  return (
    <Box
      marginBottom="SP1"
      direction="vertical"
      width={showDetails ? '100%' : 'fit-content'}
    >
      <TableListItem
        verticalPadding="xxTiny"
        horizontalPadding="xxTiny"
        border
        onClick={(e) => {
          e.stopPropagation();
          if (!supportedPreviewTypes.includes(mediaType)) {
            downloadFile();
            return;
          }
          setIsPreviewOpen(true);
        }}
        options={[
          {
            value: (
              <Box
                height={showDetails ? 48 : 36}
                overflow="hidden"
                dataHook={`file-upload-formatted-${file.mediaId}`}
              >
                <FileCard
                  file={file}
                  showDownloadCTA={showDownloadCTA}
                  showDetails={showDetails}
                />
              </Box>
            ),
          },
        ]}
      />
      {supportedPreviewTypes.includes(mediaType) ? (
        <FilePreviewModal
          file={file}
          showDetails={showDetails}
          isOpen={isPreviewOpen}
          close={() => {
            setIsPreviewOpen(false);
          }}
        />
      ) : null}
    </Box>
  );
}
