const AutomationButtons = (function () {
  const arrowDownIcon = "images/axialis/user-interface/angle-down-small.svg";
  const arrowUpIcon = "images/axialis/user-interface/angle-up-small.svg";
  let dropdowns = [];
  let toggleImages = [];
  let baseEndpointUri = "";
  let idoitRootPath = "";

  const setBaseEndpointUri = (uri) => {
    baseEndpointUri = uri;
  };

  const setIdoitRootPath = (url) => {
    idoitRootPath = url;
  };

  const startAutomation = (automationId, group) => {
    let url = `${baseEndpointUri}/${automationId}`;

    if (group) url += `/${group}`;
    return fetch(url).then((res) => res.json());
  };

  const handleStartAutomationResponse = (names) => {
    const formattedNames = names.join(", ");
    const isSingle = names.length === 1;
    return (res) => {
      if (res.ids?.length) {
        const messageKey = idoit.Translate.get(
          isSingle
            ? "LC__MODULE__SYNETICS_FLOWS__FLOW_STARTED"
            : "LC__MODULE__SYNETICS_FLOWS__FLOWS_STARTED",
        );
        idoit.Notify.success(messageKey.replace("%s", formattedNames));
      } else {
        throw new Error("Error");
      }
    };
  };

  const handleStartAutomationError = (names) => {
    const formattedNames = names.join(", ");
    const messageKey = idoit.Translate.get(
      names.length === 1
        ? "LC__MODULE__SYNETICS_FLOWS__FLOW_NOT_STARTED"
        : "LC__MODULE__SYNETICS_FLOWS__FLOWS_NOT_STARTED",
    );
    idoit.Notify.error(messageKey.replace("%s", formattedNames));
  };

  const createFlowButton = (automation, triggerName, icon) => {
    const button = document.createElement("button");
    button.type = "button";
    button.id = automation.id;
    button.classList.add("btn", "btn-secondary", "ml10");
    if (icon) {
      const img = document.createElement("img");
      img.src = idoitRootPath + icon;
      img.alt = triggerName;
      img.style.marginRight = "5px";
      button.appendChild(img);
    }
    button.appendChild(document.createTextNode(triggerName));
    button.onclick = (e) => {
      e.stopPropagation();
      e.preventDefault();
      startAutomation(automation.id)
        .then(handleStartAutomationResponse([automation.name]))
        .catch(() => handleStartAutomationError([automation.name]));
    };
    return button;
  };

  const createDropdownItem = (automation, triggerName, icon) => {
    const div = document.createElement("div");
    div.className = "flow_button_trigger__dropdownItem";

    const left = document.createElement("div");
    left.style.marginRight = "10px";
    if (icon) {
      const img = document.createElement("img");
      img.src = icon;
      img.alt = triggerName;
      img.style.width = "16px";
      img.style.height = "16px";
      left.appendChild(img);
    } else {
      const placeholder = document.createElement("span");
      placeholder.className = "flow_button_trigger__iconPlaceholder";
      left.appendChild(placeholder);
    }
    const right = document.createElement("div");
    right.textContent = triggerName;
    right.classList.add("flow_button_trigger__buttonLabel");

    div.title = idoit.Translate.get(
      "LC__MODULE__SYNETICS_FLOWS__TRIGGER_FLOW",
    ).replace("%s", triggerName);
    div.appendChild(left);
    div.appendChild(right);
    div.onclick = (e) => {
      e.stopPropagation();
      e.preventDefault();
      startAutomation(automation.id)
        .then(handleStartAutomationResponse([automation.name]))
        .catch(() => handleStartAutomationError([automation.name]));
    };
    return div;
  };

  const createDropdown = (buttons) => {
    const dropdownContainer = document.createElement("div");
    dropdownContainer.className =
      "flow_button_trigger__dropdown-container flow_button_trigger__dropdownGroup";
    buttons.forEach(({ trigger, automation }) => {
      const buttonElement = createDropdownItem(
        automation,
        trigger.name,
        trigger.icon,
      );
      buttonElement.classList.add(
        "btn",
        "btn-secondary",
        "flow_button_trigger__automationBtn",
      );
      dropdownContainer.appendChild(buttonElement);
    });
    dropdownContainer.addEventListener("click", (event) => {
      event.stopPropagation();
    });

    return dropdownContainer;
  };

  const createToggleButton = (dropdownContainer) => {
    const toggleButton = document.createElement("button");
    toggleButton.type = "button";
    toggleButton.classList.add(
      "btn",
      "btn-secondary",
      "flow_button_trigger__toggleButton",
    );
    toggleButton.style.position = "relative";

    const toggleImg = document.createElement("img");
    toggleImg.src = idoitRootPath + arrowDownIcon;
    toggleImg.alt = "";
    toggleImg.className = "flow_button_trigger__toggleImage";
    toggleButton.appendChild(toggleImg);

    toggleButton.addEventListener("click", (e) => {
      e.stopPropagation();
      dropdowns.forEach((dropdown) => {
        if (dropdown !== dropdownContainer) {
          dropdown.classList.remove("flow_button_trigger__visible");
        }
      });
      dropdownContainer.classList.toggle("flow_button_trigger__visible");
      toggleImg.src =
        idoitRootPath +
        (dropdownContainer.classList.contains("flow_button_trigger__visible")
          ? arrowUpIcon
          : arrowDownIcon);
    });

    return toggleButton;
  };

  const addButtonsGroup = (buttonsContainer, groupName, buttons) => {
    const btnGroup = document.createElement("div");
    btnGroup.className = "btn-group";
    const nameButton = document.createElement("button");
    nameButton.textContent = groupName;
    nameButton.type = "button";
    nameButton.classList.add("btn", "btn-secondary", "mr8");
    nameButton.onclick = (e) => {
      e.stopPropagation();
      e.preventDefault();
      const names = buttons.map(({ automation }) => automation.name);
      startAutomation(null, groupName)
        .then(handleStartAutomationResponse(names))
        .catch(() => handleStartAutomationError(names));
    };
    const dropdownContainer = createDropdown(buttons);
    const toggleButton = createToggleButton(dropdownContainer);
    btnGroup.appendChild(nameButton);
    btnGroup.appendChild(toggleButton);
    toggleButton.appendChild(dropdownContainer);
    return btnGroup;
  };

  const initButtons = (buttonsContainer, buttons) => {
    buttonsContainer.innerHTML = "";
    const groups = {};
    const ungroupedKey = "ungrouped" + Date.now();
    buttons.forEach((button) => {
      if (!button.trigger.group || button.trigger.group.length === 0) {
        if (!groups[ungroupedKey]) {
          groups[ungroupedKey] = [];
        }
        groups[ungroupedKey].push(button);
        return;
      }
      button.trigger.group.forEach((groupId) => {
        if (!groups[groupId]) {
          groups[groupId] = [];
        }
        groups[groupId].push(button);
      });
    });

    Object.keys(groups).forEach((group) => {
      if (group === ungroupedKey) {
        buttonsContainer.append(
          ...groups[group].map(({ trigger, automation }) => {
            const { name, icon } = trigger;
            const button = createFlowButton(automation, name, icon);
            button.classList.add("btn", "btn-secondary", "mr10");
            return button;
          }),
        );
      } else {
        buttonsContainer.append(
          addButtonsGroup(buttonsContainer, group, groups[group]),
        );
      }
    });

    dropdowns = document.querySelectorAll(
      ".flow_button_trigger__dropdown-container",
    );
    toggleImages = document.querySelectorAll(
      ".flow_button_trigger__toggleImage",
    );
    document.addEventListener("click", () => {
      dropdowns.forEach((dropdown) => {
        dropdown.classList.remove("flow_button_trigger__visible");
      });
      toggleImages.forEach((toggleBtn) => {
        toggleBtn.src = idoitRootPath + arrowDownIcon;
      });
    });
  };

  return {
    initButtons,
    setBaseEndpointUri,
    setIdoitRootPath,
  };
})();
