import fullscreen from "images/icons/fullscreen.svg";
import fullscreenOff from "images/icons/fullscreenOff.svg";

import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";

import { Button } from "components/shared/Button/Button";

export const FullscreenButton: React.FC<any> = ({ isSidebarWide }) => {

  const [active, setActive] = useState(Boolean(document.fullscreenElement));
  const [button, setButton] = useState({
    icon: fullscreen,
    inactive: "fullscreen-control-btn",
    active: "fullscreen-control-btn-active",
    type: "fullscreen",
  });

  const { t } = useTranslation();

  const handleClick = () => {
    setActive(Boolean(document.fullscreenElement));
    if (!document.fullscreenElement) {
      document.body.requestFullscreen();
    } else {
      document.exitFullscreen();
    }
  };

  useEffect(() => {
    setButton({
      icon: !active ? fullscreen : fullscreenOff,
      inactive: "fullscreen-control-btn",
      active: "fullscreen-control-btn-active",
      type: "fullscreen",
    });
  }, [active]);

  useEffect(() => {
    const onFullscreenChange = () => {
      setActive(Boolean(document.fullscreenElement));
    };
    document.addEventListener("fullscreenchange", onFullscreenChange);
    return () =>
      document.removeEventListener("fullscreenchange", onFullscreenChange);
  }, []);

  return (
    <div onFocus={(e) => e.target.blur()}
      tabIndex={-1} onClick={handleClick} className="toolbar-button-area">
      <Button
        isSidebarWide={isSidebarWide}
        button={button}
        active={active}
      ></Button>
    </div>
  );
};
