import React, { useContext, useEffect, useRef, useState } from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';
import PrivateRoute from '../../helpers/privateRoute';

import NavbarTop from '../navbar/JKNavbarTop';
import NavbarVertical from '../navbar/JKNavbarVertical';
import Footer from '../footer/JKFooter';

import { toast } from 'react-toastify';

import AppContext from '../../context/Context';
import { getPageName } from '../../helpers/utils';

import useScript from '../../hooks/useScript';
import { useDispatch } from 'react-redux';
import { addMessage } from '../../store/features/textMessagesSlice';
import { add as addNotification } from '../../store/features/notificationSlice';

import { useAuth } from '../../context/UserAuth';

import HomePage from '../page/JKHomePage';

import JKHelp from '../page/JKHelp';
import JKPrivacy from '../page/JKPrivacy';
//import JKPeople from '../page/JKPeople';
import JKPeopleFilter from '../page/JKPeopleFilter';
import JKNotifications from '../page/JKNotifications';
import JKMessageModal from '../profile/JKMessageModal';
import JKUnsubscribe from '../page/JKUnsubscribe';

import JKMusicSessions from '../page/JKMusicSessions';
import JKNewMusicSession from '../page/JKNewMusicSession';

//import loadable from '@loadable/component';
//const DashboardRoutes = loadable(() => import('../../layouts/JKDashboardRoutes'));
//const PublicRoutes = loadable(() => import('../../layouts/JKPublicRoutes')) 

const Msg = ({ closeToast, toastProps, title }) => (
  <div>
    <a href='#'>{title}</a>
  </div>
)

function JKDashboardMain() {
  const { isFluid, isVertical, navbarStyle } = useContext(AppContext);
  const isKanban = getPageName('kanban');

  const { isAuthenticated, currentUser, setCurrentUser, logout } = useAuth();

  const scriptLoaded = useRef(false)

  const [showMessageModal, setShowMessageModal] = useState(false)
  const [messageUser, setMessageUser] = useState(null)

  useEffect(() => {
    //DashboardRoutes.preload();
    //PublicRoutes.preload();
  }, []);

  const dispatch = useDispatch();

  const initJKScripts = () => {
    if(scriptLoaded.current){
      return
    }
    
    const app = window.JK.JamKazam();
    
    const jamServer = new window.JK.JamServer(app, function(event_type) {
      console.log('EVENT_TYPE', event_type);
    });
    jamServer.initialize();
    
    window.JK.initJamClient(app);
    const clientInit = new window.JK.ClientInit();
    clientInit.init();

    window.JK.JamServer.connect() // singleton here defined in JamServer.js
      .done(function() {
        console.log('Jamserver connected...');
        //_initAfterConnect(true);
      })
      .fail(function() {
        console.log('Jamserver connection error...');
        //_initAfterConnect(false);
      });

    registerTextMessageCallback();
    registerFriendRequest();
    registerFriendRequestAccepted();

    scriptLoaded.current = true
  };

  const registerTextMessageCallback = () => {
    window.JK.JamServer.registerMessageCallback(window.JK.MessageType.TEXT_MESSAGE, function(header, payload) {
      console.log('registerTextMessageCallback payload', payload);
      //console.log('registerTextMessageCallback header', header);
      const msg = {
        id: payload.text_message_id,
        message: payload.msg,
        senderId: payload.sender_id,
        senderName: payload.sender_name,
        receiverId: window.currentUser.id,
        receiverName: window.currentUser.first_name,
        createdAt: payload.created_at,
        sent: true
      };

      dispatch(addMessage(msg));

      //toast(<Msg title={`${msg.senderName} has sent a new message`} />)
      toast.info(`${msg.senderName} has sent a new message`, {
        hideProgressBar: true,
        closeOnClick: true,
        pauseOnHover: true,
        onClick: () => {
          setMessageUser({ id: msg.senderId, name: msg.senderName })
          setShowMessageModal(true)
        }
      }) 

      handleNotification(payload, header.type);
    });
  };

  const registerFriendRequest = () => {
    window.JK.JamServer.registerMessageCallback(window.JK.MessageType.FRIEND_REQUEST, function(header, payload) {
      console.log('registerFriendRequest payload', payload);
      console.log('registerFriendRequest header', header);
      handleNotification(payload, header.type);
    });
  };

  const registerFriendRequestAccepted = () => {
    window.JK.JamServer.registerMessageCallback(window.JK.MessageType.FRIEND_REQUEST_ACCEPTED, function(
      header,
      payload
    ) {
      console.log('registerFriendRequestAccepted payload', payload);
      console.log('registerFriendRequestAccepted header', header);
      handleNotification(payload, header.type);
    });
  };

  const handleNotification = (payload, type) => {
    const notification = {
      description: type,
      notification_id: payload.notification_id,
      session_id: payload.session_id,
      friend_request_id: payload.friend_request_id,
      formatted_msg: payload.msg,
      text_message_id: payload.text_message_id,
      message: payload.msg,
      source_user_id: payload.sender_id,
      source_user: {
        name: payload.sender_name
      },
      created_at: payload.created_at
    };

    try {
      dispatch(addNotification(notification));
    } catch (error) {
      console.log(error);
    }
  };

  useScript(`${process.env.REACT_APP_CLIENT_BASE_URL}/client_scripts`, initJKScripts);

  return (
    <div className={isFluid || isKanban ? 'container-fluid' : 'container'}>
      {isVertical && <NavbarVertical isKanban={isKanban} navbarStyle={navbarStyle} />}

      <div className="content">
        <NavbarTop />
        <Switch>
          <Route path="/" exact component={HomePage} />
          <Route path="/privacy" component={JKPrivacy} />
          <Route path="/help" component={JKHelp} />
          <Route path="/unsubscribe" exact component={JKUnsubscribe} />
          <PrivateRoute path="/friends" component={JKPeopleFilter} />
          <PrivateRoute path="/sessions/new" component={JKNewMusicSession} />
          <PrivateRoute path="/sessions" component={JKMusicSessions} />
          <PrivateRoute path="/notifications" component={JKNotifications} />
          {/*Redirect*/}
          <Redirect to="/errors/404" />
         
        </Switch>
        {!isKanban && <Footer />}
      </div>
      { messageUser && 
        <JKMessageModal show={showMessageModal} setShow={setShowMessageModal} user={messageUser} />
      }
      
      {/* <SidePanelModal path={location.pathname} /> */}
    </div>
  );
}

export default JKDashboardMain;
