import { useEffect, useRef, useState } from 'react';
import './App.css'
import { Editor, type EditorState } from './Editor'
import { initialEditorState, nonEmptyEditorState, tripleFunctionCallEditorState } from "./configurations";
import { CommandContext } from './CommandContext';

export function App() {
  const [history, setHistory] = useState([initialEditorState]);
  // const [history, setHistory] = useState([nonEmptyEditorState]);
  // const [history, setHistory] = useState([tripleFunctionCallEditorState]);

  const [future, setFuture] = useState<EditorState[]>([]);

  const pushHistory = (s: EditorState) => {
    setHistory(history.concat([s]));
    setFuture([]);
  };

  const onUndo = () => {
    setFuture(future.concat(history.at(-1)!)); // add
    setHistory(history.slice(0,-1)); // remove
  };
  const onRedo = () => {
    setHistory(history.concat(future.at(-1)!)); // add
    setFuture(future.slice(0,-1)); // remove
  };

  const onKeyDown = (e) => {
    if (e.key === "Z" && e.ctrlKey) {
      if (e.shiftKey) {
        if (future.length > 0) {
          onRedo();
        }
      }
      else {
        if (history.length > 1) {
          onUndo();
        }
      }
      e.preventDefault();
    }
  };

  useEffect(() => {
    window['APP_STATE'] = history; // useful for debugging
  }, [history]);

  useEffect(() => {
    window.onkeydown = onKeyDown;
  }, []);

  const commands = [
    ["call"     , "[c] call"              ],
    ["eval"     , "[u] [Tab] [Enter] eval"],
    ["transform", "[t] transform"         ],
    ["let"      , "[=] let ... in ..."    ],
  ];

  const [highlighted, setHighlighted] = useState(
    commands.map(() => false));

  const doHighlight = Object.fromEntries(commands.map(([id], i) => {
    return [id, () => {
      setHighlighted(h => h.with(i, true));
      setTimeout(() => setHighlighted(h => h.with(i, false)), 100);
    }];
  }));

  return (
    <>
      <header>
        <button disabled={history.length===1} onClick={onUndo}>Undo ({history.length-1}) [Ctrl+Z]</button>
        <button disabled={future.length===0} onClick={onRedo}>Redo ({future.length})  [Ctrl+Shift+Z]</button>
        Commands:
        {
          commands.map(([_, descr], i) =>
            <span key={i} className={'command' + (highlighted[i] ? (' highlighted') : '')}>
              {descr}
            </span>)
        }
      </header>

      <main>
        <CommandContext value={doHighlight}>
          <Editor
            state={history.at(-1)!}
            setState={pushHistory}
            onResolve={() => {}}
            onCancel={() => {}}
            filter={() => true}
            focus={true}
          />
        </CommandContext>
      </main>

      <footer>
        <a href="https://deemz.org/git/joeri/dope2-webapp">Source code</a>
      </footer>
    </>
  )
}
