import { 
  useCallback, 
  useEffect, 
  useState 
} from 'react';
import { useOutletContext } from 'react-router-dom';
import Metadata from './Metadata';
import Warning from '../../common/display/Warning';
import apiLoader from '../../../services/utilities/apiLoader';
import useLoadingMessages from '../../hooks/useLoadingMessages';

function Editor({
  loadNotes,
  noteId, 
  setCurrentNote,
  toggleNote
}) {

  const nowRunning = 'utilities/notes/Editor.jsx';
  const errorNumber = 354;
  
  const [state, setState] = useState({
    loaded: false,
    note: {},
  });

  const { 
    loaded, 
    note, 
  } = state;

  const { 
    handleError,
    setLoadingMessages
  } = useOutletContext();
  const { 
    addLoadingMessage, 
    removeLoadingMessage 
  } = useLoadingMessages(setLoadingMessages);

  const loadNote = useCallback(async () => {

    const context = `${nowRunning}.loadNote`;
    const loadingMessage = 'loading the note...';

    try {

      addLoadingMessage(loadingMessage);
      const api = 'utilities/notes/get-by-id';
      const payload = { noteId };
      const { data } = await apiLoader({ api, payload });

      if (!data.success) {

        handleError(data.failure, context, errorNumber, true);
        return;

      }

      setState((prevState) => ({
        ...prevState,
        note: data.note
      }));

    } catch (e) {

      handleError(e, context, errorNumber);

    } finally {

      removeLoadingMessage(loadingMessage);

    }
  }, [addLoadingMessage, handleError, noteId, removeLoadingMessage]);

  useEffect(() => {

    const context = `${nowRunning}.useEffect`;

    const runThis = async () => {

      if (!loaded) {

        setState((prevState) => ({
          ...prevState,
          loaded: true,
        }));
        await loadNote();

      }

    };

    runThis().catch((e) => handleError(e, context, errorNumber));

  }, [handleError, loaded, loadNote]);

  try {

    if (!loaded) return null;

    if (loaded && !note) return <Warning message="the note was not located" />;

    return (

      <>

        <Metadata
          loadNotes={loadNotes}
          note={note}
          noteId={noteId}
          setCurrentNote={setCurrentNote}
          toggleNote={toggleNote}
        />
        
      </>

    );

  } catch (e) {

    handleError(e, nowRunning, );

  }

}

export default Editor;