import CloudDownloadIcon from "@mui/icons-material/CloudDownload";
import { Button, Paper, Typography } from "@mui/material";
import { filesize } from "filesize";
import { FileApi, UploadedFile } from "../api/FileApi";
import { AsyncWidget } from "./AsyncWidget";
import React from "react";

export function AsyncFileViewerWidget(p: {
  fileID: number;
}): React.ReactElement {
  const [file, setFile] = React.useState<UploadedFile | undefined>();

  const load = async () => {
    setFile(await FileApi.GetFile(p.fileID));
  };

  return (
    <AsyncWidget
      loadKey={p.fileID}
      load={load}
      errMsg="Failed to load file information!"
      build={() => <FileViewerWidget file={file!} />}
    />
  );
}

export function FileViewerWidget(p: {
  file: UploadedFile;
}): React.ReactElement {
  return (
    <FileViewer
      url={FileApi.DownloadURL(p.file)}
      downloadUrl={FileApi.DownloadURL(p.file, true)}
      {...p.file}
    />
  );
}

type ViewerProps = {
  url: string;
  downloadUrl: string;
} & UploadedFile;

function FileViewer(p: ViewerProps): React.ReactElement {
  // Image
  if (p.mime_type.startsWith("image/")) return <ImageViewer {...p} />;
  // PDF
  else if (p.mime_type === "application/pdf") return <PDFViewer {...p} />;
  // Default viewer
  else return <DefaultViewer {...p} />;
}

function ImageViewer(p: ViewerProps): React.ReactElement {
  return (
    <img
      src={p.url}
      style={{ maxWidth: "100%", width: "fit-content", margin: "auto" }}
    />
  );
}

function PDFViewer(p: ViewerProps): React.ReactElement {
  // eslint-disable-next-line react-dom/no-missing-iframe-sandbox
  return <iframe style={{ flex: 1 }} src={p.url} />;
}

function DefaultViewer(p: ViewerProps): React.ReactElement {
  return (
    <Paper
      elevation={3}
      style={{
        margin: "10px",
        padding: "10px",
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <Typography variant="h5" gutterBottom>
        <CloudDownloadIcon fontSize="large" />
      </Typography>
      <Typography variant="caption" gutterBottom>
        {filesize(p.file_size)}
      </Typography>
      <a href={p.downloadUrl} target="_blank" referrerPolicy="no-referrer">
        <Button variant="outlined">Download</Button>
      </a>
    </Paper>
  );
}
