import { useEffect, useState } from 'react';
import './App.css'
import Bouton from "./interface/Bouton";
import CatHistory from "./interface/CatHistory";
import Chats from "./interface/Chats";
import useWebSocket, { ReadyState } from 'react-use-websocket';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

function App() {

  const [status, setStatus] = useState({})
  const [history, setHistory] = useState({})
  const [ignoreNextToast, setIgnoreNextToast] = useState(false)
  const { sendMessage, lastMessage, readyState } = useWebSocket('ws://localhost:3001');

  useEffect(() => {
    if (readyState === ReadyState.CLOSED) {
      toast.error('Connection lost, please refresh the page', {
        autoClose: false,
      });
    }
  }, [readyState]);

  useEffect(() => {
    if (lastMessage === null) return;
    const data = JSON.parse(lastMessage.data);
    console.log(data);
    if(data.status) setStatus(data.status);
    if(data.history) setHistory(data.history);
    else updateHistory(data.status)
  }, [lastMessage]);

  return (
    <div className="App">
        <div>
            <h1>La chatière de Pina !</h1>
        </div>
        <Bouton locked={status.locked} sendMessage={sendMessage} setIgnoreNextToast={setIgnoreNextToast} />
        <Chats catsInside={status.catsInside} sendMessage={sendMessage} setIgnoreNextToast={setIgnoreNextToast} />
        <CatHistory history={history} />
        <ToastContainer />
    </div>
  )

  function updateHistory(newStatus) {
    const date = new Date();

    if(newStatus.catsInside < status.catsInside) {
      const log = {date: date, event: 'left'};
      if(!ignoreNextToast) toast('🐾 A pina just left the house');
      setHistory((prevHistory) => ({...prevHistory, catLog: [log, ...prevHistory.catLog]}));
    }else if(newStatus.catsInside > status.catsInside) {
      const log = {date: date, event: 'entered'};
      if(!ignoreNextToast) toast('🐈 A pina just entered the house');
      setHistory((prevHistory) => ({...prevHistory, catLog: [log, ...prevHistory.catLog]}));
    }else if(newStatus.locked !== status.locked) {
      const log = newStatus.locked ? {date: date, event: 'locked'} : {date: date, event: 'unlocked'};
      if(!ignoreNextToast) toast(newStatus.locked ? '🔴 Cat door locked 🔴' : '🟢 Cat door unlocked 🟢');
      setHistory((prevHistory) => ({...prevHistory, lockLog: [log, ...prevHistory.lockLog]}));
    }
    setIgnoreNextToast(false);
  }
}

export default App
