import { RuleListInputAdder } from "./RuleListInputAdder";
import { useState } from "react";
import FileInput from "./FileInput";
import { MdOutlineSave } from "react-icons/md";
import React from "react";
import { GrammarAdderInput, Rule } from "../types";

const GrammarAdder = ({
  save,
  fileAdd,
}: GrammarAdderInput) => {
  function emptyRule() {
    return { id: -1, leftSymbol: "", rightSide: [], root: false };
  }
  const removeRule = () => {
    setRules(rules.filter((val, ind) => ind !== rules.length - 1));
  };

  const addRule = () => {
    if (rules == null) {
      setRules([emptyRule()]);
      return;
    }

    setRules([...rules, emptyRule()]);
  };
  const [uri, setUri] = useState("");
  const [rules, setRules] = useState<Rule[]>([]);
  const [root, setRoot] = useState(-1);
  const [file, setFile] = useState<File|null>(null);
  const [fileInput, setFileInput] = useState(false);
  const [text, setText] = useState("");
  const handleTextSubmit = (
    e:
      | React.FormEvent<HTMLFormElement>
      | React.MouseEvent<SVGElement, MouseEvent>
  ) => {
    e.preventDefault();
    if (!uri) {
      return;
    }
    for (let index = 0; index < rules.length; index++) {
      const rule = rules[index];
      if (rule.leftSymbol == null || rule.rightSide === null) {
        return;
      }
    }
    if (root === -1 || root >= rules.length) {
      save(uri, rules, null);
    } else {
      rules[root].root = true;
      save(uri, rules, rules[root]);
    }

    setUri("");
    setRoot(-1);
    setRules([]);
  };
  const changeInput = () => {
    setFileInput(!fileInput);
  };

  return (
    <>
      <button onClick={changeInput}>
        {" "}
        {fileInput ? "TEXT INPUT " : "FILE INPUT"}
      </button>
      {fileInput ? (
        <FileInput
          fileAdd={fileAdd}
          file={file}
          setFile={setFile}
          setText={setText}
          text={text}
          newDiff={false}
        />
      ) : (
        <>
          <form onSubmit={handleTextSubmit}>
            <input
              onChange={(e) => {
                setUri(e.target.value);
              }}
              type="text"
              placeholder="Set grammar uri"
              className="transparent"
            />
            <MdOutlineSave onClick={handleTextSubmit} />
            {rules.length > 0 && (
              <RuleListInputAdder
                rules={rules}
                setRules={setRules}
                setRoot={setRoot}
              />
            )}
          </form>
          <p>
            <button onClick={addRule}> ADD RULE</button>{" "}
            {rules.length > 0 && (
              <button onClick={removeRule}> REMOVE RULE</button>
            )}
          </p>
        </>
      )}
    </>
  );
};

export default GrammarAdder;
