import "./DocumentModal.scss";

import { FC, useCallback, useEffect, useState } from "react";

import Button from "@/components/generics/button/Button";
import { GoX } from "react-icons/go";
import Modal from "react-modal";
import PdfViewer from "./PdfViewer";
import Spinner from "@/components/generics/spinner/Spinner";
import { getDocumentPdf } from "@/api/documents/documentsApi";

export interface DocumentModalProps {
  isOpen: boolean;
  file_id: string | null;
  file_xml_name: string;
  filename: string;
  setIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
}
const customStyles = {
  content: {
    top: "50%",
    left: "50%",
    right: "auto",
    bottom: "auto",
    transform: "translate(-50%, -50%)",
    borderRadius: "15px",
    minWidth: "600px",
  },
};

export const DocumentModal: FC<DocumentModalProps> = ({
  isOpen,
  file_id,
  filename,
  setIsOpen,
}) => {
  const [file, setFile] = useState<{ file: Blob; filename: string } | null>(
    null
  );
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);

  const handleRead = useCallback(() => {
    setIsLoading(true);

    if (file_id !== null) {
      getDocumentPdf(null, file_id, filename)
        .then((file) => {
          setIsError(false);
          setFile(file);
        })
        .catch(() => {
          setIsError(true);
        })
        .finally(() => {
          setIsLoading(false);
        });
    }

  }, [file_id, filename]);

  useEffect(() => {
    if (isOpen) {
      handleRead();
    }
  }, [handleRead, isOpen]);

  function closeModal() {
    setIsOpen(false);
    setFile(null);
  }

  return (
    <Modal
      style={customStyles}
      isOpen={isOpen}
      ariaHideApp={false}
      onRequestClose={closeModal}
    >
      <div className={"document_modal"}>
        <div className="actions">
          <h3 className="filename" title={filename}>
            {filename}
          </h3>
          <Button
            name={""}
            onClick={closeModal}
            icon={<GoX />}
            buttonType="link"
          />
        </div>
        {isLoading || isError ? (
          <div
            style={{
              display: "flex",
              gap: "10px",
              alignItems: "center",
              flexDirection: "column",
            }}
          >
            {!isError ? (
              <>
                Загрузка документа
                <Spinner />
              </>
            ) : (
              <>Ошибка загрузки документа</>
            )}
          </div>
        ) : (
          <PdfViewer file={file?.file ?? null} />
        )}
      </div>
    </Modal>
  );
};
