import React, { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import "../styles/Loader.css";

const loaderVideoPath = new URL("../assets/video/taganai.mp4", import.meta.url)
  .href;

const Loader = ({
  loadingStatus = null,
  loadingProgress = null,
  onToggleDebug,
}) => {
  const [showLoadingInfo, setShowLoadingInfo] = useState(false);

  useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.key === "F3") {
        event.preventDefault();
        setShowLoadingInfo((prev) => !prev);
      }
      if (event.key === "F4") {
        event.preventDefault();
        onToggleDebug?.();
      }
    };

    window.addEventListener("keydown", handleKeyDown);

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [onToggleDebug]);

  const getStatusText = () => {
    if (!loadingStatus) return "Данные не загружены";

    if (loadingProgress) {
      const percentage = Math.round(
        (loadingProgress.current / loadingProgress.total) * 100,
      );
      return `${loadingStatus} [${loadingProgress.current}/${loadingProgress.total}] ${percentage}%`;
    }

    return loadingStatus;
  };

  return createPortal(
    <div
      className="loading-gif"
      style={{ zIndex: 2147483647, backgroundColor: "black" }}
    >
      {showLoadingInfo && <div className="loading-info">{getStatusText()}</div>}
      <video
        autoPlay
        loop
        muted
        playsInline
        src={loaderVideoPath}
        alt="Loading"
        className="error-gif"
        style={{ width: "100%", height: "100%", objectFit: "cover" }}
      />
    </div>,
    document.body,
  );
};

export default Loader;
