import { detectFileType } from "@/server/lib/detect-type-of-file";
import { Flex, Image, Loader, Modal } from "@mantine/core";
import { useEffect, useState } from "react";
import notification from "./notificationGlobal";

export default function ModalFile({
  open,
  onClose,
  folder,
  fileName,
}: {
  open: boolean;
  onClose: () => void;
  folder: string;
  fileName: string;
}) {
  const [viewFile, setViewFile] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(false);
  const [typeFile, setTypeFile] = useState<string>("");
  const [error, setError] = useState<boolean>(false);

  useEffect(() => {
    if (open && fileName) {
      loadImage();
    }
  }, [open, fileName]);

  const loadImage = async () => {
    try {
      setViewFile("");
      setLoading(true);

      // detect type of file
      const { ext, type } = detectFileType(fileName);
      setTypeFile(type || "");

      // load file
      const urlApi =
        "/api/pengaduan/image?folder=" + folder + "&fileName=" + fileName;
      const res = await fetch(urlApi);
      if (!res.ok) {
        setError(true);
        return notification({
          title: "Error",
          message: "Failed to load image",
          type: "error",
        });
      }
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);

      setViewFile(url);
    } catch (err) {
      setError(true);
      notification({
        title: "Error",
        message: "Failed to load image",
        type: "error",
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (error) {
      onClose();
    }
  }, [error]);

  return (
    <Modal
      opened={open}
      onClose={onClose}
      overlayProps={{ backgroundOpacity: 0.55, blur: 3 }}
      size="xl"
      withCloseButton
      removeScrollProps={{ allowPinchZoom: true }}
      title="File"
    >
      {loading && (
        <Flex justify="center" align="center" h={200}>
          <Loader />
        </Flex>
      )}
      {viewFile && (
        <>
          {typeFile == "pdf" ? (
            <embed
              src={viewFile}
              type="application/pdf"
              width="100%"
              height="950"
            />
          ) : (
            <Image radius="md" h={300} fit="contain" src={viewFile} />
          )}
        </>
      )}
    </Modal>
  );
}
