import "./PlayerStyles.css";
import React, { useEffect, useState } from "react";
import { useHistory, useParams } from "react-router-dom";

import { connectSession } from "store/reducers/ActionCreator";
import { useAppDispatch, useAppSelector } from "hooks/redux";
import useWindowDimensions from "hooks/useWindowDimensions";
import useMobile from "hooks/useMobile";

import { Sidebar } from "components/pages/Stream/components/Sidebar/Sidebar";
import { Player } from "components/pages/Stream/components/Player/Player";

type link = {
  id: string;
};



export const PlayerComponent: React.FC<any> = ({ cleanErrors, handleDisconnect, loadStream }) => {
  const { isMobile } = useMobile();
  const windowDimensions = useWindowDimensions();
  const width = windowDimensions.width;
  const height = windowDimensions.height;
  const [popup, setPopup] = useState(false);
  const { playerCount } = useAppSelector((state) => state.sessionReducer)




  const { id } = useParams<link>();
  const dispatch = useAppDispatch();
  const history = useHistory()


  useEffect(() => {
    dispatch(connectSession(id)).unwrap().then(() => {
      loadStream()
    }).catch((res) => {
      alert(res);
      history.push('/')
    })
    return () => {
      dispatch(cleanErrors());
      handleDisconnect()
      window.removeEventListener("change ", (event: any) => {
        setPopup(false);
      });
    };
  }, []);



  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>
      )}
      <Player></Player>
      <Sidebar
        handleDisconnect={handleDisconnect}
        players={playerCount}
        heightDevice={height}
        isMobile={isMobile}
      ></Sidebar>
    </>
  );
};

