import { ObjectUtils } from '@sankhyalabs/core';
import { ApplicationUtils } from '@sankhyalabs/ezui/dist/collection/utils';
import { h } from '@stencil/core';
import { TAB_NAMES } from '../../../lib/utils/constants';
export class SnkDynaformGuidesConfigurator {
  constructor() {
    this.sortLogic = (a, b) => {
      var _a, _b;
      const orderA = (_a = a.order) !== null && _a !== void 0 ? _a : Number.MAX_VALUE;
      const orderB = (_b = b.order) !== null && _b !== void 0 ? _b : Number.MAX_VALUE;
      return orderA - orderB;
    };
    this.handleAddGuide = () => {
      this.createNewGuide.emit();
    };
    this.mainGuide = undefined;
    this.visibleGuides = [];
    this.hiddenGuides = [];
    this.guidesList = [];
    this.selectedGuide = undefined;
    this.messagesBuilder = undefined;
  }
  observeGuidesList(newGuides) {
    this.initGuidesConfig(newGuides);
  }
  observeSelectedGuide(newGuide) {
    this.guideSelected.emit(newGuide);
  }
  componentWillLoad() {
    this.initGuidesConfig(this.guidesList);
  }
  getMessage(key, params) {
    return this.messagesBuilder.getMessage(key, params);
  }
  initGuidesConfig(newGuides) {
    const visibleAux = newGuides.filter(guide => guide.visible && guide.name !== TAB_NAMES.main);
    const hiddenAux = newGuides.filter(guide => !guide.visible && guide.name !== TAB_NAMES.main);
    this.visibleGuides = [...visibleAux].sort(this.sortLogic);
    this.hiddenGuides = [...hiddenAux].sort(this.sortLogic);
    this.mainGuide = newGuides.find(g => g.name === TAB_NAMES.main);
  }
  handleSelectGuide(guide, evt) {
    evt.stopPropagation();
    this.selectedGuide = guide;
  }
  toggleGuideVisibility(guide, evt) {
    evt.stopPropagation();
    const updatedGuide = Object.assign(Object.assign({}, guide), { visible: !guide.visible });
    let visibleAux;
    let hiddenAux;
    if (guide.visible) {
      visibleAux = this.visibleGuides.filter(g => g.name !== guide.name);
      hiddenAux = [...this.hiddenGuides, updatedGuide];
    }
    else {
      visibleAux = [...this.visibleGuides, updatedGuide];
      hiddenAux = this.hiddenGuides.filter(g => g.name !== guide.name);
    }
    this.applyGuidesUpdate([...visibleAux, ...hiddenAux]);
  }
  adjustListOrder(guideList) {
    return guideList.map((g, index) => (Object.assign(Object.assign({}, g), { order: index })));
  }
  applyGuidesUpdate(updatedGuideList) {
    let newGuidesList = this.adjustListOrder(updatedGuideList);
    if (this.mainGuide) {
      newGuidesList = [this.mainGuide, ...newGuidesList];
    }
    if (!ObjectUtils.equals(newGuidesList, this.guidesList)) {
      this.guideListChanged.emit(newGuidesList);
    }
  }
  async handleDeleteGuide(guide, e) {
    e.stopPropagation();
    const title = this.getMessage('snkFormConfig.confirm.title');
    const message = this.getMessage('snkFormConfig.confirm.deleteGuide').replace('{0}', guide.label);
    const canRemove = await ApplicationUtils.confirm(title, message);
    if (!canRemove)
      return;
    this.guideDeleted.emit(guide);
    const deletedMessage = this.getMessage('snkFormConfig.info.successfullyGuideDeleted').replace('{0}', guide.label);
    ApplicationUtils.info(deletedMessage);
  }
  buildTabs() {
    const tabs = [];
    if (this.mainGuide) {
      tabs.push({ tabKey: this.mainGuide.name, label: this.mainGuide.label, index: 0 });
    }
    this.visibleGuides.forEach((guide, i) => {
      tabs.push({
        tabKey: guide.name,
        label: guide.label,
        index: (this.mainGuide ? 1 : 0) + i,
      });
    });
    return tabs;
  }
  handleTabChange(tab) {
    var _a;
    if (!tab)
      return;
    const guide = this.guidesList.find(g => g.name === tab.tabKey);
    if (guide && guide.name !== ((_a = this.selectedGuide) === null || _a === void 0 ? void 0 : _a.name)) {
      this.selectedGuide = guide;
    }
  }
  handleReorder(reorderedTabs) {
    // __main fica fixo no índice 0; se o usuário tentou movê-lo, recolocar
    const visibleReordered = reorderedTabs
      .filter(t => { var _a; return t.tabKey !== ((_a = this.mainGuide) === null || _a === void 0 ? void 0 : _a.name); })
      .map(t => this.visibleGuides.find(g => g.name === t.tabKey))
      .filter(Boolean);
    this.applyGuidesUpdate([...visibleReordered, ...this.hiddenGuides]);
  }
  renderTabActions() {
    return this.visibleGuides.map((guide, i) => {
      const slotIndex = (this.mainGuide ? 1 : 0) + i;
      const isProtected = guide.isCustom || guide.isDetail;
      return (h("div", { key: guide.name, slot: `tab${slotIndex}`, class: "tab-actions", onClick: (e) => e.stopPropagation() }, h("ez-button", { mode: "icon", class: "ez-button--tertiary tab-action-btn", size: "small", iconName: "eye-off", title: this.getMessage('snkFormConfig.guidesConfigurator.actions.hide'), onClick: (e) => this.toggleGuideVisibility(guide, e) }), h("ez-button", { mode: "icon", class: "ez-button--tertiary tab-action-btn", size: "small", iconName: "delete", isDisabled: isProtected, title: isProtected
          ? this.getMessage('snkFormConfig.guidesConfigurator.canNotDeleteCustomGuide')
          : this.getMessage('snkFormConfig.guidesConfigurator.actions.delete'), onClick: (e) => this.handleDeleteGuide(guide, e) })));
    });
  }
  renderHiddenGuidesBar() {
    if (this.hiddenGuides.length === 0)
      return null;
    return (h("div", { class: "hidden-guides-bar" }, h("span", { class: "hidden-guides-label" }, this.getMessage('snkFormConfig.guidesConfigurator.hiddenGuides'), ":"), this.hiddenGuides.map(guide => {
      const isProtected = guide.isCustom || guide.isDetail;
      return (h("div", { key: guide.name, class: "hidden-guide-chip", title: guide.label }, h("span", { class: "chip-label", onClick: (e) => this.handleSelectGuide(guide, e) }, guide.label), h("ez-button", { mode: "icon", class: "ez-button--tertiary", size: "small", iconName: "eye", title: this.getMessage('snkFormConfig.guidesConfigurator.actions.show'), onClick: (e) => this.toggleGuideVisibility(guide, e) }), h("ez-button", { mode: "icon", class: "ez-button--tertiary", size: "small", iconName: "delete", isDisabled: isProtected, title: isProtected
          ? this.getMessage('snkFormConfig.guidesConfigurator.canNotDeleteCustomGuide')
          : this.getMessage('snkFormConfig.guidesConfigurator.actions.delete'), onClick: (e) => this.handleDeleteGuide(guide, e) })));
    })));
  }
  render() {
    var _a;
    const tabs = this.buildTabs();
    return (h("div", { class: "guides-tab-configurator" }, h("div", { class: "tab-bar-row" }, h("ez-tabselector", { class: "guides-tabselector", tabs: tabs, selectedTab: (_a = this.selectedGuide) === null || _a === void 0 ? void 0 : _a.name, reorderable: true, onEzChange: (evt) => this.handleTabChange(evt.detail), onEzReorder: (evt) => this.handleReorder(evt.detail) }, this.renderTabActions()), h("ez-button", { label: this.getMessage('snkFormConfig.guidesConfigurator.createNewGuide'), variant: "secondary", size: "medium", leftIconName: "plus", onClick: this.handleAddGuide })), this.renderHiddenGuidesBar()));
  }
  static get is() { return "snk-dynaform-guides-configurator"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["snk-dynaform-guides-configurator.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["snk-dynaform-guides-configurator.css"]
    };
  }
  static get properties() {
    return {
      "guidesList": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "IGuideConfig[]",
          "resolved": "IGuideConfig[]",
          "references": {
            "IGuideConfig": {
              "location": "import",
              "path": "../FormConfigHelper"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "defaultValue": "[]"
      },
      "selectedGuide": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "IGuideConfig",
          "resolved": "IGuideConfig",
          "references": {
            "IGuideConfig": {
              "location": "import",
              "path": "../FormConfigHelper"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        }
      },
      "messagesBuilder": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "SnkMessageBuilder",
          "resolved": "SnkMessageBuilder",
          "references": {
            "SnkMessageBuilder": {
              "location": "import",
              "path": "../../../lib/message/SnkMessageBuilder"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        }
      }
    };
  }
  static get states() {
    return {
      "mainGuide": {},
      "visibleGuides": {},
      "hiddenGuides": {}
    };
  }
  static get events() {
    return [{
        "method": "guideSelected",
        "name": "guideSelected",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "IGuideConfig",
          "resolved": "IGuideConfig",
          "references": {
            "IGuideConfig": {
              "location": "import",
              "path": "../FormConfigHelper"
            }
          }
        }
      }, {
        "method": "guideListChanged",
        "name": "guideListChanged",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "IGuideConfig[]",
          "resolved": "IGuideConfig[]",
          "references": {
            "IGuideConfig": {
              "location": "import",
              "path": "../FormConfigHelper"
            }
          }
        }
      }, {
        "method": "guideDeleted",
        "name": "guideDeleted",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "IGuideConfig",
          "resolved": "IGuideConfig",
          "references": {
            "IGuideConfig": {
              "location": "import",
              "path": "../FormConfigHelper"
            }
          }
        }
      }, {
        "method": "createNewGuide",
        "name": "createNewGuide",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "void",
          "resolved": "void",
          "references": {}
        }
      }];
  }
  static get watchers() {
    return [{
        "propName": "guidesList",
        "methodName": "observeGuidesList"
      }, {
        "propName": "selectedGuide",
        "methodName": "observeSelectedGuide"
      }];
  }
}
