import ImageIcon from "@mui/icons-material/Image";
import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";
import { Button, IconButton } from "@mui/material";
import { filesize } from "filesize";
import React from "react";
import { FileApi, UploadedFile } from "../api/FileApi";
import { FileViewerDialog } from "../dialogs/FileViewerDialog";
import { AsyncWidget } from "./AsyncWidget";

export function UploadedFileWidget(p: {
  file_id: number;
  small?: boolean;
}): React.ReactElement {
  const [file, setFile] = React.useState<UploadedFile | null>(null);

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

  return (
    <AsyncWidget
      errMsg="Failed"
      build={() => <UploadedFileWidgetInner file={file!} small={p.small} />}
      loadKey={p.file_id}
      load={load}
    />
  );
}

function UploadedFileWidgetInner(p: {
  small?: boolean;
  file: UploadedFile;
}): React.ReactElement {
  const [open, setOpen] = React.useState(false);
  return (
    <>
      <FileViewerDialog
        open={open}
        file={p.file}
        onClose={() => {
          setOpen(false);
        }}
      />
      {p.small ? (
        <IconButton
          onClick={() => {
            setOpen(true);
          }}
        >
          <FileIcon file={p.file} />
        </IconButton>
      ) : (
        <Button
          startIcon={<FileIcon file={p.file} />}
          onClick={() => {
            setOpen(true);
          }}
        >
          {p.file.file_name} ({filesize(p.file.file_size)})
        </Button>
      )}
    </>
  );
}

function FileIcon(p: { file: UploadedFile }): React.ReactElement {
  return p.file.mime_type === "application/pdf" ? (
    <PictureAsPdfIcon />
  ) : (
    <ImageIcon />
  );
}
