/* eslint-disable react-hooks/exhaustive-deps */
// Copyright Epic Games, Inc. All Rights Reserved.

import { useEffect, useRef, useState } from "react";
import {
  Config,
  AllSettings,
  PixelStreaming,
} from "@epicgames-ps/lib-pixelstreamingfrontend-ue5.3";
import { Trans } from "react-i18next";

export interface PixelStreamingWrapperProps {
  initialSettings?: Partial<AllSettings>;
}

export const PixelStreamingWrapper = ({
  initialSettings,
}: PixelStreamingWrapperProps) => {
  // A reference to parent div element that the Pixel Streaming library attaches into:
  const videoParent = useRef<HTMLDivElement>(null);

  // Pixel streaming library instance is stored into this state variable after initialization:
  const [pixelStreaming, setPixelStreaming] = useState<PixelStreaming>();

  // A boolean state variable that determines if the Click to play overlay is shown:
  const [clickToPlayVisible, setClickToPlayVisible] = useState<boolean>(false);
  const [videoInitialized, setVideoInitialized] = useState<boolean>(false);

  // Run on component mount:
  useEffect(() => {
    if (videoParent.current) {
      // Attach Pixel Streaming library to videoParent element:
      const config = new Config({ initialSettings });
      const streaming = new PixelStreaming(config, {
        videoElementParent: videoParent.current,
      });

      streaming.addEventListener("videoInitialized", () => {
        setVideoInitialized(true);
      });

      // register a playStreamRejected handler to show Click to play overlay if needed:
      streaming.addEventListener("playStreamRejected", () => {
        setClickToPlayVisible(true);
      });

      // Save the library instance into component state so that it can be accessed later:
      setPixelStreaming(streaming);

      document.getElementById("hiddenInput")?.remove();
      document.getElementById("editTextButton")?.remove();

      // Clean up on component unmount:
      return () => {
        try {
          streaming.disconnect();
        } catch {
          //
        }
      };
    }
  }, []);

  return (
    <div className="relative w-screen h-screen">
      <div className="w-full h-[100svh]" ref={videoParent} />
      {!videoInitialized && (
        <div className="absolute top-0 left-0 w-full h-full flex justify-center items-center">
          <Trans i18nKey="streamBuffering">Буферизация потока</Trans>
        </div>
      )}
      {clickToPlayVisible && (
        <div className="absolute top-0 left-0 w-full h-full flex justify-center items-center z-10 bg-[#131317]">
          <div className="flex flex-col justify-center items-center w-[400px] p-10 space-y-10  rounded-lg">
            <div className="space-y-4 text-center">
              <p className="text-4xl font-gilroy">
                <Trans i18nKey="demoStarted">Демонстрация начата</Trans>
              </p>
              <p className="text-[#C5C7CE]">
                <Trans i18nKey="clickToContinue">
                  Нажмите, чтобы продолжить
                </Trans>
              </p>
            </div>

            <button
              onClick={() => {
                pixelStreaming?.play();
                setClickToPlayVisible(false);
              }}
            >
              <svg
                width="88"
                height="88"
                viewBox="0 0 88 88"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <g filter="url(#filter0_b_0_1121)">
                  <path
                    d="M55.6667 43.9999L34.6668 57.9999L34.6668 30L55.6667 43.9999Z"
                    fill="#F2F2F2"
                    stroke="#F2F2F2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                  <rect
                    x="0.5"
                    y="0.5"
                    width="87"
                    height="87"
                    rx="43.5"
                    stroke="url(#paint0_linear_0_1121)"
                  />
                </g>
                <defs>
                  <filter
                    id="filter0_b_0_1121"
                    x="-20"
                    y="-20"
                    width="128"
                    height="128"
                    filterUnits="userSpaceOnUse"
                    colorInterpolationFilters="sRGB"
                  >
                    <feFlood floodOpacity="0" result="BackgroundImageFix" />
                    <feGaussianBlur in="BackgroundImageFix" stdDeviation="10" />
                    <feComposite
                      in2="SourceAlpha"
                      operator="in"
                      result="effect1_backgroundBlur_0_1121"
                    />
                    <feBlend
                      mode="normal"
                      in="SourceGraphic"
                      in2="effect1_backgroundBlur_0_1121"
                      result="shape"
                    />
                  </filter>
                  <linearGradient
                    id="paint0_linear_0_1121"
                    x1="88"
                    y1="-2.6226e-06"
                    x2="2.6226e-06"
                    y2="88"
                    gradientUnits="userSpaceOnUse"
                  >
                    <stop stopColor="#BC75FF" />
                    <stop offset="1" stopColor="#798FFF" />
                  </linearGradient>
                </defs>
              </svg>
            </button>
          </div>
        </div>
      )}
    </div>
  );
};
