import "./PlayerStyles.css";
import React, { useEffect, useState, useRef } from "react";
import { useHistory, useParams } from "react-router-dom";
import useWindowDimensions from "hooks/useWindowDimensions";
import { load } from "utils/app";
import useMobile from "hooks/useMobile";
import { Sidebar } from "components/pages/Stream/Sidebar/Sidebar";

import { connectSession } from "store/reducers/ActionCreator";
import { useAppDispatch, useAppSelector } from "hooks/redux";
import { sessionSlice } from "store/reducers/sessionSlice";
import { Player } from "../Player/Player";

type link = {
  id: string;
};

export const PlayerComponent: React.FC<any> = ({ closeStream }) => {
  const frameRef = useRef<HTMLIFrameElement>()
  const { isMobile } = useMobile();
  const windowDimensions = useWindowDimensions();
  const width = windowDimensions.width;
  const height = windowDimensions.height;
  const [popup, setPopup] = useState(false);
  const history = useHistory()
  console.log(popup);

  const { id } = useParams<link>();
  const [click, setClick] = useState(false);
  const dispatch = useAppDispatch();
  const { cleanErrors } = sessionSlice.actions;

  useEffect(() => {
    dispatch(connectSession(id)).then((res: any) => {
      load()
      if (res.error) {
        alert(res.payload);
      }
    });
    return () => {
      dispatch(cleanErrors());
      window.removeEventListener("change ", (event: any) => {
        setPopup(false);
      });
    };
  }, []);

  const { url } = useAppSelector((state) => state.sessionReducer);

  const exitPopup = () => {
    setClick((prev) => !prev);
  };

  useEffect(() => {
    if (isMobile) {
      if (width < height) {
        setPopup(true);
      } else {
        setPopup(false);
      }
    }
  }, [width, height, isMobile]);



  return (
    <>
      {popup && (
        <div className="popup-screen" style={{ height: height }}>
          <h2>Переверните устройство</h2>
        </div>
      )}
      <div id="playerUI" className="noselect">
        <div id="player"></div>
        <div id="overlay">
        </div>
      </div>
      <Player></Player>
      <Sidebar
        heightDevice={height}
        isMobile={isMobile}
        exitPopup={click}
        closeStream={closeStream}
      ></Sidebar>
    </>
  );
};
function getElementById(arg0: string) {
  throw new Error("Function not implemented.");
}

