const beforeUnloadHandler = (event) => {
  event.preventDefault();
};

const forms = document.querySelectorAll("form");

for (let form of forms) {
  let inputs = form.querySelectorAll("input");
  for (input of inputs) {
    input.addEventListener("input", (event) => {
      window.addEventListener("beforeunload", beforeUnloadHandler);
    });
  }

  form.addEventListener("submit", (event) => {
    window.removeEventListener("beforeunload", beforeUnloadHandler);
  });
  form.addEventListener("reset", (event) => {
    window.removeEventListener("beforeunload", beforeUnloadHandler);
  });

  let categorySelect = form.querySelector(".category-select");
  if (categorySelect) {
    let input = categorySelect.querySelector("select");
    let icon = categorySelect.querySelector("span");
    let icons = JSON.parse(input.dataset.icons);

    function setIcon(event) {
      icon.className = `ri-${icons[input.value] || "folder"}-line`;
    }
    setIcon();
    input.addEventListener("input", setIcon);
    form.addEventListener("reset", (event) => {
      setTimeout(setIcon, 0);
    });
  }
  let accountSelect = form.querySelector(".account-select");
  if (accountSelect) {
    let input = accountSelect.querySelector("select");
    let icon = accountSelect.querySelector("span");
    let icons = JSON.parse(input.dataset.icons);

    function setIcon(event) {
      icon.className = `ri-${icons[input.value] || "bank"}-line`;
    }
    setIcon();
    input.addEventListener("input", setIcon);
    form.addEventListener("reset", (event) => {
      setTimeout(setIcon, 0);
    });
  }

  let iconSelect = form.querySelector(".icon-select");
  if (iconSelect) {
    let input = iconSelect.querySelector("input");
    let icon = iconSelect.querySelector("span");
    let icons = Array.from(iconSelect.querySelector("datalist").options).map(
      (opt) => opt.value,
    );

    function setIcon(event) {
      icon.className = `ri-${
        icons.includes(input.value) ? input.value : "square"
      }-line`;
    }
    setIcon();
    input.addEventListener("input", setIcon);
    form.addEventListener("reset", (event) => {
      setTimeout(setIcon, 0);
    });
  }

  let ac_json = form.querySelector("#autocomplete");
  if (ac_json) {
    let autocomplete_data = JSON.parse(ac_json.textContent);
    let fields = form.querySelectorAll("[name]");
    function clearMod(event) {
      event.target.classList.add("mod");
      event.target.removeEventListener("input", clearMod);
    }
    function setMod() {
      for (let f of fields) {
        f.addEventListener("input", clearMod);
      }
    }
    setMod();
    form.addEventListener("reset", (event) => {
      for (let f of fields) {
        f.classList.remove("mod", "autocompleted");
      }
      setMod();
    });

    let old_values = [];

    let field = form.querySelector(`[name="${autocomplete_data.field}"]`);
    field.addEventListener("change", (event) => {
      if (field.value in autocomplete_data.data) {
        old_values = [];
        for (let comp of autocomplete_data.data[field.value]) {
          let f = form.querySelector(`[name="${comp.field}"]`);
          if (!f.classList.contains("mod")) {
            old_values.push({ field: f, value: f.value });

            f.value = comp.value;
            f.dispatchEvent(new Event("input"));
            f.animate([{ borderColor: "var(--green)" }, {}], 750);
            f.classList.remove("mod");
            f.classList.add("autocompleted");
            f.addEventListener("input", clearMod);
            function ccAutocomplete(event) {
              document.removeEventListener("keyup", cancelAutocomplete);
              for (comp of old_values) {
                comp.field.removeEventListener("input", ccAutocomplete);
              }
            }
            f.addEventListener("input", ccAutocomplete);
          }
        }
        function cancelAutocomplete(event) {
          if (event.code == "Escape") {
            for (comp of old_values) {
              let f = comp.field;
              f.value = comp.value;
              f.dispatchEvent(new Event("input"));
              f.animate([{ borderColor: "var(--red)" }, {}], 750);
              f.classList.remove("mod");
              f.classList.remove("autocompleted");
              f.addEventListener("input", clearMod);
            }
            document.removeEventListener("keyup", cancelAutocomplete);
          }
        }
        document.addEventListener("keyup", cancelAutocomplete);
        form.addEventListener("reset", (event) => {
          document.removeEventListener("keyup", cancelAutocomplete);
        });
      }
    });
  }
}

let accounts = document.querySelector("dl.accounts");
if (accounts) {
  let toggle = accounts.querySelector("input#show-archived-accounts");
  if (toggle) {
    accounts.classList.toggle("show-archive", toggle.checked);
    toggle.addEventListener("change", (event) => {
      accounts.classList.toggle("show-archive", toggle.checked);
    });
  }
}

const filterForm = document.querySelector("form.filter");
if (filterForm) {
  const accountSelect = filterForm.querySelector("[name='account']");
  const statementSelect = filterForm.querySelector("[name='statement']");
  if (!statementSelect.disabled) {
    accountSelect.addEventListener("input", (event) => {
      statementSelect.value = "";
      statementSelect.disabled = true;
    });
    filterForm.addEventListener("reset", (event) => {
      statementSelect.disabled = false;
    });
  }
  let disableStatement = false;
  filterForm.addEventListener("submit", (event) => {
    for (element of filterForm.elements) {
      if (
        element.value == "" ||
        (disableStatement && element.name == "statement")
      ) {
        if (element.name == "account") {
          disableStatement = true;
        }
        element.disabled = true;
      }
    }
  });
}
