import Grid from '@mui/material/Grid'
import { makeStyles } from '@material-ui/core'
import { useSelector } from 'react-redux'
import { useState,useRef } from 'react'
import io from 'socket.io-client';
import Moveable from "react-moveable";
import { OnDrag } from "react-moveable";

import LeftBar from './LeftBar'
import CentralBar from './CentralBar'
import RightBar from './RightBar'
import CallBar from './CallBar';
import { getRightIsOpen } from '../../redux/control/selector'
import { getChatMemo } from '../../redux/chat/selector'
import { getNightMode } from '../../redux/authorization/selector'
import wallpaper from '../../img/wallpaper.jpg'
import wallpaperNight from '../../img/wallpaperNight.jpg'
import { prodSocketURL } from '../../helpers';

const socket = io(prodSocketURL)

const useStyles = makeStyles({
  container: {
    minHeight: '100vh',
    maxHeight: '100vh',
  },
  centralAndRight: {
    display:'flex'
  },
  myVideo: {
    width: 250,
    height: 'auto',
    cursor: 'pointer',
    position: 'absolute',
    top: 0,
    left: 0,
    zIndex: 150,
    backgroundColor:'#28e217',
  },  
})

const HomePage = () => {
  const classes = useStyles()
  const rightIsOpen = useSelector(getRightIsOpen)
  const myVideoRef = useRef<any | null>(null);
  const chatDivRef = useRef<any | null>(null)
  const nightMode = useSelector(getNightMode)
  const { companionId } = useSelector(getChatMemo)
  const [callStatus,setCallStatus] = useState<string>('')
  const backgroundImage =  `url(${nightMode ? wallpaperNight : wallpaper})`
  const handleStartCall = () => setCallStatus('requesting')

return (
    <Grid className={classes.container} container spacing={0} >
      <video className={classes.myVideo} ref={myVideoRef} playsInline autoPlay muted/>
      <Moveable
        target={myVideoRef.current}
        draggable={true}
        throttleDrag={0}
        hideDefaultLines={true}
        renderDirections={[]}
        rotationPosition="none"
        origin={false}
        onDrag={({ target, transform }: OnDrag) =>
          target!.style.transform = transform }
      />
      <CallBar callStatus={callStatus} setCallStatus={setCallStatus} socket={socket} myVideoRef={myVideoRef}/>
      <LeftBar chatDivRef={chatDivRef} />
      {companionId ?
      <Grid item lg={9} className={classes.centralAndRight}>
        <CentralBar rightIsOpen={rightIsOpen} chatDivRef={chatDivRef}
          companionId={companionId} backgroundImage={backgroundImage}
          handleStartCall={handleStartCall}/>
        <RightBar rightIsOpen={rightIsOpen} chatDivRef={chatDivRef} />
      </Grid> :
      <Grid item lg={9} style={{backgroundImage}}/>}
    </Grid>
    )
}

export default HomePage