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

import { connectSession } from "store/reducers/ActionCreator";
import { useAppDispatch, useAppSelector } from "hooks/redux";
import { sessionSlice } from "store/reducers/sessionSlice";
import useWindowDimensions from "hooks/useWindowDimensions";
import { load as loadStream, usersArray } from "utils/app";
import useMobile from "hooks/useMobile";

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

type link = {
  id: string;
};



export const PlayerComponent: React.FC<any> = ({ }) => {
  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 [click, setClick] = useState(false);
  const dispatch = useAppDispatch();
  const { cleanErrors } = sessionSlice.actions;


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



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


  return (
    <>
    <span>{playerCount}</span>
      {popup && (
        <div className="popup-screen" style={{ height: height }}>
          <h2>Переверните устройство</h2>
        </div>
      )}
      <Player></Player>
      <Sidebar
        players={playerCount}
        heightDevice={height}
        isMobile={isMobile}
        exitPopup={click}
      ></Sidebar>
    </>
  );
};

