import {
  Button,
  Card,
  DialogActions,
  DialogContent,
  DialogTitle,
  Typography
} from "@mui/material";
import ImageViewer from "common/ImageViewer";
import ResponsiveDialog from "common/ResponsiveDialog";
import { pond } from "protobuf-ts/pond";
import { useFileControllerAPI } from "providers";
import { useEffect, useState } from "react";

interface FileReferences {
  images: pond.FileReference[];
  other: pond.FileReference[];
}

interface Props {
  contractKey: string;
  transactionKey: string;
  open: boolean;
  onClose: () => void;
}

export default function ContractTransactionFile(props: Props) {
  const { contractKey, transactionKey, open, onClose } = props;
  const fileController = useFileControllerAPI();
  const [fileRefs, setFileRefs] = useState<FileReferences>({
    images: [],
    other: []
  });

  useEffect(() => {
    //retrieve the files for the passed in uuids
    if (transactionKey) {
      fileController
        .listFileRefs(transactionKey, [contractKey, transactionKey], ["contract", "transaction"])
        .then(resp => {
          let fileRefs: FileReferences = {
            images: [],
            other: []
          };
          resp.data.fileRefs.forEach(fileRef => {
            if (fileRef.metadata && fileRef.metadata.contentType.split("/")[0] === "image") {
              fileRefs.images.push(fileRef);
            } else {
              fileRefs.other.push(fileRef);
            }
          });
          setFileRefs(fileRefs);
        });
    }
  }, [contractKey, transactionKey, fileController]);

  const close = () => {
    onClose();
  };

  return (
    <ResponsiveDialog open={open} onClose={close}>
      <DialogTitle>Attached Files</DialogTitle>
      <DialogContent>
        <Typography>Attached Images</Typography>
        {fileRefs.images.map(file => (
          <Card key={file.uuid} style={{ width: "100%" }}>
            <ImageViewer image={file} width={"100%"} />
          </Card>
        ))}
      </DialogContent>
      <DialogActions>
        <Button onClick={close}>Close</Button>
      </DialogActions>
    </ResponsiveDialog>
  );
}
