import React, { useEffect } from 'react'
import { io } from 'socket.io-client'

import { Box } from '@chakra-ui/react'
import { Canvas } from 'react-three-fiber'

import MenuOverlay from './MenuOverlay'
import Error from './Error'
import Scene from '../3d'

import useStore, { UserTransforms } from '../store'
import useLogin from '../hooks/useLogin'
import { Redirect } from 'react-router-dom'

const Museo: React.FC = () => {
  const { response, isLoading } = useLogin<{ authenticated: boolean }>('auth/check')

  const setSocket = useStore((state) => state.setSocket)
  const setError = useStore((state) => state.setError)
  const error = useStore((state) => state.error)
  const setUserTransforms = useStore((state) => state.setUserTransforms)

  useEffect(() => {
    if (!response || isLoading) {
      return
    }
    const socket = io()
    setSocket(socket)

    socket.on('disconnect', () => setError('SOCKET'))
    socket.on('broadcast-transforms', (payload: UserTransforms) => {
      setUserTransforms(payload)
    })

    return () => {
      socket.close()
      setSocket(null)
    }
  }, [response, isLoading])

  if (isLoading || !response) return null

  return response.authenticated === false ? (
    <Redirect to="/" />
  ) : (
    <Box w="100vw" h="100vh">
      {error ? (
        <Error />
      ) : (
        <>
          <MenuOverlay />
          <Canvas
            colorManagement
            concurrent
            gl={{
              antialias: false,
              alpha: false,
            }}
            camera={{
              fov: 45,
              near: 0.25,
              far: 200,
            }}
          >
            <Scene />
          </Canvas>
        </>
      )}
    </Box>
  )
}

export default Museo
