import React, { ReactNode, useState } from "react";
import "./Editor.css";
import { Highlight } from "./highlight";
import { buildShadow } from "./shadow";
import OrgAst from "./OrgAst";

function Editor({ defaultValue = "I have a text value." }) {
  function handleChange(event: React.ChangeEvent<HTMLTextAreaElement>) {
    setValue(event.target.value);
  }

  const [value, setValue] = useState(defaultValue);

  const [highlights, setHighlights] = useState<Array<Highlight>>([]);

  function addHighlight(start: number, end: number) {
    let new_highlights = [...highlights, new Highlight(start, end)];
    new_highlights.sort(function (a,b) {
      if (a.start < b.start) return -1;
      if (a.start > b.start) return 1;
      return 0;
    });
    setHighlights(new_highlights);
  }

  function clearHighlights() {
    setHighlights([]);
  }

  if (highlights.length === 0) {
    addHighlight(1, 5);
  }

  return (
    <div className="Editor">
      <div className="Editor-textwrapper">
        <textarea
          onChange={handleChange}
          className="Editor-textarea"
          value={value}
        />
        <div className="Editor-underlay">{buildShadow(highlights, value)}</div>
      </div>
      <OrgAst addHighlight={addHighlight} value={value} />
    </div>
  );
}

export default Editor;
