import { lazy, Suspense , useEffect } from 'react';
import { BrowserRouter, Switch } from 'react-router-dom';
import { ToastContainer } from 'react-toastify';
import { useSelector, useDispatch } from 'react-redux';
import { MuiPickersUtilsProvider } from '@material-ui/pickers';
import DateFnsUtils from '@date-io/date-fns';

import s from './App.module.css';
import { getToken } from './redux/authorization/selector'
import { getChat } from './redux/chat/selector'
import { asyncLogout, asyncCurrentUser } from './redux/authorization/operations'
import { setToken, onlineUser,typingChat } from './api-data'
import PrivateRoute from './components/reusableComponents/Routes/PrivateRoute';
import PublicRoute from './components/reusableComponents/Routes/PublicRoute';
import { Load,CLoad } from './components/reusableComponents/Loader/Loader';

const HomePage = lazy(
  () =>
    import(
      './components/HomePage' /* webpackChunkName: "HomePage" */
    ),
);

const AuthPage = lazy(
  () =>
    import(
      './components/AuthPage' /* webpackChunkName: "AuthPage" */
    ),
);

function App() {
  const token = useSelector(getToken)
  const { companionId } = useSelector(getChat)
  const dispatch = useDispatch()
  const handleTypingClose = async () => {
    companionId&& await typingChat(companionId, false)
  }

  useEffect(() => {
    if (!localStorage.isChecked) localStorage.isChecked = 'true'
    localStorage.removeItem('isNew')
  }, [])

   useEffect(() => {
    if (token && localStorage.isChecked === 'true') {
      setToken.set(token)
      dispatch(asyncCurrentUser())
    }
   }, [dispatch, token])

  useEffect(() => {
    const handleKeepIn = async () => {
      if (localStorage.isChecked === 'false') {
        dispatch(asyncLogout())
      } else if (localStorage.isChecked === 'true') {
          await onlineUser()
      }
    }
    window.addEventListener("beforeunload",handleKeepIn)
    return () => window.removeEventListener("beforeunload", handleKeepIn)

  }, [dispatch])

  useEffect(() => {
    const handleTypingChat = async () => await typingChat(companionId,false)
    window.addEventListener("beforeunload",handleTypingChat)
    return () => window.removeEventListener("beforeunload", handleTypingChat)

  }, [companionId])

  return (
  <div onMouseLeave={handleTypingClose} className={s.appWrapper}>
    <MuiPickersUtilsProvider utils={DateFnsUtils}>
      <Suspense fallback={<Load/>}>
        <BrowserRouter>
          <Switch>
            <PrivateRoute exact path="/">
              <HomePage/>
            </PrivateRoute>
              <PublicRoute  path={'/z/'} restricted>
                <AuthPage />
              </PublicRoute>
          </Switch>
        </BrowserRouter>
        <CLoad/>
      </Suspense>
      <ToastContainer
      position="top-right"
      autoClose={5000}
      hideProgressBar={false}
      newestOnTop={false}
      closeOnClick
      rtl={false}
      pauseOnFocusLoss
      draggable
      pauseOnHover
      />    
    </MuiPickersUtilsProvider>
  </div>
)}


export default App;
