import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useNavigate } from 'react-router-dom';
import { apiUrl, wsUrl } from '../apiTools.jsx';
import { useFixLinks } from '../clientStuff.jsx';
import { useLoggedIn } from '../AuthProvider.jsx';
import useWebSocket, { ReadyState } from 'react-use-websocket';

import Page from '../page/Page.jsx';
import MessageFeed from './MessageFeed.jsx';
import Sidebar from './Sidebar.jsx';
import CommandEntry from './CommandEntry.jsx';

function Live({editing, ...props}) {
  const navigate = useNavigate();
  const loggedIn = useLoggedIn();
  
  const [ messageHistory, setMessageHistory ] = useState([]);
  const [ currentNumber, setCurrentNumber ] = useState(1);
  const [ connecting, setConnecting ] = useState(true);

  const { sendMessage, lastMessage, lastJsonMessage, readyState } = useWebSocket(`${wsUrl}/embody`, {
    onClose: () => setConnecting(false)
  }, connecting);
  
  useEffect(() => {
    if (lastMessage !== null) {
      console.log(lastMessage);
      setMessageHistory((prev) => prev.concat(lastMessage));
      
      if (lastMessage.data.startsWith("location change to: ")) {
        const num = Number(lastMessage.data.replace("location change to: #", ""));
        setCurrentNumber(num);
      }
    }
  }, [lastMessage]);

  // spread this return value on <a/> elements in order to make them navigate 
  const commandLinkClick = (e) => {
    if (e.target.tagName != "A") { return; }
    if (!e.target.href.includes(window.location.origin)) { return; }
    e.preventDefault();

    const localLink = e.target.href.replace(window.location.origin, "");
    const targetString = localLink.replace("/", "");
    const targetNumber = Number(targetString);
    
    if (targetNumber != 0 && targetNumber != NaN) {
      const warpMessage = `warp #${targetString}`;
      console.log(`clicked a link, executing "warp #${targetString}"`);
      sendMessage(warpMessage);
      return;
    }
    
    navigate(e.target.href.replace(window.location.origin, ""));
  };

  return (
    <>
      <Page editing={editing} number={currentNumber} linkClick={commandLinkClick} {...props} />
      <MessageFeed messages={messageHistory}>
        <button disabled={connecting} onClick={() => setConnecting(true)}>Reconnect</button>
        <button onClick={()=> setMessageHistory([])}>Clear History</button>
      </MessageFeed>
      <Sidebar pagenumber={currentNumber} hidden="true" sendWord={(word) => setCommand((command + " " + word).trim())}>
      </Sidebar>
      <CommandEntry onSubmit={(w) => { console.log(w); sendMessage(w); } }/>
    </>
  );
}

export default Live;