import React, { Dispatch, SetStateAction, useEffect, useState } from 'react';
import { MainMenu } from '../MainMenu/MainMenu';
import { ContainerModel } from '../../Interfaces/IContainerModel';
import { Editor } from '../Editor/Editor';
import { IEditorState } from '../../Interfaces/IEditorState';
import { LoadState } from './Actions/Load';
import { LoadEditor, NewEditor } from './Actions/MenuActions';
import { DEFAULT_CONFIG, DEFAULT_MAINCONTAINER_PROPS } from '../../utils/default';

// App will never have props
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface IAppProps {
  root: Element | Document
}

function UseHTTPGETStatePreloading(
  isLoaded: boolean,
  setEditorState: Dispatch<SetStateAction<IEditorState>>,
  setLoaded: Dispatch<SetStateAction<boolean>>
): void {
  useEffect(() => {
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const state = urlParams.get('state');

    if (state === null) {
      return;
    }

    if (!isLoaded) {
      fetch(state)
        .then(
          async(response) => await response.json(),
          (error) => { throw new Error(error); }
        )
        .then((data: IEditorState) => {
          LoadState(data, setEditorState, setLoaded);
        }, (error) => { throw new Error(error); });
    }
  });
};

export function App(props: IAppProps): JSX.Element {
  const [isLoaded, setLoaded] = useState<boolean>(false);

  const defaultMainContainer = new ContainerModel(
    null,
    DEFAULT_MAINCONTAINER_PROPS
  );

  const [editorState, setEditorState] = useState<IEditorState>({
    configuration: DEFAULT_CONFIG,
    history: [{
      lastAction: '',
      mainContainer: defaultMainContainer,
      selectedContainerId: defaultMainContainer.properties.id,
      typeCounters: {},
      symbols: new Map(),
      selectedSymbolId: ''
    }],
    historyCurrentStep: 0
  });

  UseHTTPGETStatePreloading(isLoaded, setEditorState, setLoaded);

  if (isLoaded) {
    return (
      <div>
        <Editor
          root={props.root}
          configuration={editorState.configuration}
          history={editorState.history}
          historyCurrentStep={editorState.historyCurrentStep}
        />
      </div>
    );
  }

  return (
    <div className='mainmenu-bg'>
      <MainMenu
        newEditor={() => NewEditor(
          setEditorState, setLoaded
        )}
        loadEditor={(files: FileList | null) => LoadEditor(
          files,
          setEditorState,
          setLoaded
        )}
      />
    </div>
  );
};
