import html from "../../services/html.js";
import { buildConfirmCancelButtons, getModalInputValue, isModalCheckboxChecked, openPluginModal, } from "./modal-controller.js";
import t from "../../i18n/index.js";
const confirm = ".modal__button--confirm";
const disabled = "modal__button--disabled";
const error = ".modal__error";
const visible = "modal__error--visible";
export default class SettingsModal {
    constructor(onChange, values, variants, defaultVariantName) {
        this.onClose = () => {
            const idInput = this.root.querySelector('[name="id"]');
            idInput?.removeEventListener("input", this.checkId);
        };
        this.checkId = () => {
            const idInput = this.root.querySelector('[name="id"]');
            const id = idInput.value;
            const valid = id === "" ||
                id === this.values.id ||
                document.getElementById(id) === null;
            const confirmButton = this.root.querySelector(confirm);
            const errorContainer = this.root.querySelector(error);
            if (valid) {
                confirmButton.classList.remove(disabled);
                errorContainer.classList.remove(visible);
            }
            else {
                confirmButton.classList.add(disabled);
                errorContainer.classList.add(visible);
            }
        };
        this.updateSettings = () => {
            const confirmButton = this.root.querySelector(confirm);
            if (confirmButton?.classList.contains(disabled)) {
                return;
            }
            const id = getModalInputValue(this.modal, "id");
            const variant = getModalInputValue(this.modal, "variant");
            const tags = getModalInputValue(this.modal, "tags");
            const hidden = isModalCheckboxChecked(this.modal, "hidden");
            const attributes = this.values.attributes
                ? Object.keys(this.values.attributes).map((key) => {
                    const attributeInput = this.root.querySelector(`[name="${key}"]`);
                    const value = attributeInput?.value || "";
                    return { property: key, value };
                })
                : [];
            this.onChange({ variant, id, tags, hidden, attributes });
        };
        this.onChange = onChange;
        this.variants = variants;
        this.defaultVariantName = defaultVariantName;
        this.values = values;
    }
    init() {
        this.modal = openPluginModal({
            icon: "tune",
            title: t("modals.settings.title"),
            content: template(this.values, this.variants, this.defaultVariantName),
            onClose: this.onClose,
            buttons: buildConfirmCancelButtons({
                confirmLabel: t("common.validate"),
                onConfirm: this.updateSettings,
                autofocus: true,
            }),
        });
        this.root = this.modal.shadowRoot;
        const idInput = this.root.querySelector('[name="id"]');
        idInput.addEventListener("input", this.checkId);
    }
}
function template(values, variants, defaultVariantName) {
    const { id, tags, variant, hidden, tagsLabel, allowedTags, allowMultipleTags, attributes, } = values;
    return html `
    <style>
      .modal__form {
        width: 400px;
        max-width: 100%;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
      }

      .modal__form-title {
        flex: 0 0 auto;
        display: flex;
        align-items: center;
        gap: 6px;
        color: var(--eden-grey-500);
        font-size: 15px;
        font-weight: 700;
      }

      .modal__form-title-icon {
        flex: 0 0 16px;
        width: 16px;
        height: 16px;
        fill: currentcolor;
      }

      .modal__error {
        display: none;
        margin: -15px 0 10px 0;
        padding-top: 3px;
        color: var(--eden-red-400);
        font-size: 12px;
      }

      .modal__error--visible {
        display: block;
      }

      .modal__tip {
        margin-top: -15px;
        font-size: 13px;
        color: var(--eden-grey-500);
      }
    </style>
    <div class="modal__form">
      ${renderVariants(variants, defaultVariantName, variant)}
      ${renderAttributes(attributes)}
      ${renderTags(tags, tagsLabel, allowedTags, allowMultipleTags)}
      <eden-input
        type="text"
        label="${t("modals.settings.identifier")}"
        name="id"
        value="${id}"
      ></eden-input>
      <div class="modal__error">${t("modals.settings.identifier-error")}</div>
      <eden-checkbox
        label="${t("modals.settings.hide-block")}"
        name="hidden"
        checked="${hidden}"
      ></eden-checkbox>
    </div>
  `;
}
function renderAttributes(attributes) {
    if (!attributes)
        return "";
    return Object.keys(attributes)
        .map((key) => {
        const { name, value, placeholder, options, allowMultipleOptions, helper, } = attributes[key];
        const helperAttribute = helper ? `helper="${helper}"` : "";
        if (options) {
            const multiple = allowMultipleOptions ? "multiple" : "";
            return html `<eden-tag-manager
          ${multiple}
          name="${key}"
          label="${name}"
          value="${value}"
          options="${options}"
          ${helperAttribute}
        ></eden-tag-manager>`;
        }
        return html `<eden-input
        type="text"
        label="${name}"
        name="${key}"
        value="${value}"
        placeholder="${placeholder}"
        ${helperAttribute}
      ></eden-input>`;
    })
        .join("");
}
function renderOptions(options, value) {
    return options
        .map((option) => {
        return html `<option
        value=${option.cssClass}
        ${value === option.cssClass ? "selected" : ""}
      >
        ${option.name}
      </option> `;
    })
        .join("");
}
function renderVariants(variants, defaultVariantName = "Par défaut", variant) {
    if (!variants)
        return "";
    const value = variant ? `value="${variant}"` : "";
    return html `
    <eden-input
      type="select"
      label="${t("modals.settings.variant")}"
      name="variant"
      ${value}
    >
      <option value="">${defaultVariantName}</option>
      ${renderOptions(variants, variant)}
    </eden-input>
  `;
}
function renderTags(tags, tagsLabel, allowedTags, allowMultipleTags) {
    if (allowedTags) {
        const multiple = allowMultipleTags ? "multiple" : "";
        const label = tagsLabel || (allowMultipleTags ? "Tags" : "Tag");
        return html `<eden-tag-manager
      ${multiple}
      name="tags"
      label="${label}"
      value="${tags}"
      options="${allowedTags}"
    ></eden-tag-manager>`;
    }
    const placeholderAttribute = tagsLabel
        ? ""
        : "placeholder='tag-1, tag-2, tag-3'";
    return html `
    <eden-input
      type="text"
      label="${tagsLabel || "Tag(s)"}"
      name="tags"
      value="${tags}"
      ${placeholderAttribute}
    ></eden-input>
  `;
}
