import { proxyCustomElement, HTMLElement, forceUpdate, h } from '@stencil/core/internal/client';
import { ObjectUtils, ApplicationContext } from '@sankhyalabs/core';
import { ModalAction } from '@sankhyalabs/ezui/dist/collection/components/ez-modal-container';
import { ApplicationUtils } from '@sankhyalabs/ezui/dist/collection/utils';
import { P as PersonalizedFilterUtils, D as DefaultFilter } from './PersonalizedFilterUtils.js';
import { F as FilterNumberVariation } from './filterNumberVariation.js';
import { F as FilterItemType } from './filter-item-type.enum.js';
import { A as ActionDefaultFilter, d as defineCustomElement$2 } from './snk-default-filter2.js';
import { F as FilterType, d as defineCustomElement$1 } from './snk-filter-modal-item2.js';

function hasActiveElements(value) {
  var _a;
  const list = Array.isArray(value) ? value : value === null || value === void 0 ? void 0 : value.elements;
  return ((_a = list === null || list === void 0 ? void 0 : list.filter((val) => val === null || val === void 0 ? void 0 : val.check)) === null || _a === void 0 ? void 0 : _a.length) > 0;
}
function getInvalidFilters(filters) {
  if (!filters || filters.length === 0) {
    return [];
  }
  return filters.filter(item => {
    if (!item.required) {
      return false;
    }
    if (item.type === FilterItemType.MULTI_LIST) {
      return !hasActiveElements(item.value);
    }
    return !item.value;
  });
}
function validateFilters(filters) {
  var _a;
  const notValidFilters = (_a = getInvalidFilters(filters)) !== null && _a !== void 0 ? _a : [];
  return notValidFilters.length === 0;
}

const snkFilterModalCss = "ez-modal{--ez-modal-content-padding:24px 12px}.snk-filter-modal__container{min-width:344px;overflow:hidden}.snk-filter-modal__content{display:flex;flex-direction:column;gap:var(--space--medium, 12px);padding-right:var(--space--3xs, 4px)}.snk-filter-modal__collapsible-box{border:var(--border--small, 1px solid) var(--color--strokes, #DCE0E8);border-radius:var(--border--radius-medium);padding:var(--space--medium, 12px) var(--space--small, 6px)}.snk-filter-modal__rendered-items{max-height:760px}.snk-filter-modal__rendered-items::-webkit-scrollbar{width:var(--space--small);min-width:var(--space--small);max-width:var(--space--small)}";

const SnkFilterModal = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this._isUserSup = false;
    this.filters = [];
    this.filtersWithError = [];
    this.getMessage = undefined;
    this.configName = undefined;
    this.filterConfig = undefined;
    this.opened = false;
    this.applyFilters = undefined;
    this.closeModal = undefined;
    this.addPersonalizedFilter = undefined;
    this.editPersonalizedFilter = undefined;
    this.deletePersonalizedFilter = undefined;
    this.filtersToDelete = [];
    this.filterDefaultToDelete = undefined;
    this.disablePersonalizedFilter = undefined;
    this.filterCustomConfigInterceptor = undefined;
  }
  filterConfigChangeHandler(newValue) {
    this.filters = ObjectUtils.copy(newValue);
    this.validateFilters();
  }
  /**
   * Emitido quando um filtro personalizado é deletado.
   */
  deletePersonalizedFilterListener(event) {
    this.filtersToDelete.push(event.detail);
  }
  getCustomMessage(key, params) {
    var _a;
    return (_a = this.getMessage) === null || _a === void 0 ? void 0 : _a.call(this, `snkFilterBar.filterModal.${key}`, params);
  }
  //TODO: tratar clear all dos filtros personalizados
  handleClearAll() {
    const { customFilters, quickFilters, otherFilters, multiListFilters } = this.filters.reduce((acc, filter) => {
      if (filter.type === FilterItemType.MULTI_LIST) {
        acc.multiListFilters.push(filter);
        return acc;
      }
      if (filter.filterType === FilterType.QUICK_FILTER) {
        acc.quickFilters.push(filter);
        return acc;
      }
      if (filter.filterType === FilterType.CUSTOM_FILTER) {
        acc.customFilters.push(filter);
        return acc;
      }
      if (filter.filterType === FilterType.OTHER_FILTERS) {
        acc.otherFilters.push(filter);
        return acc;
      }
      return acc;
    }, { quickFilters: [], customFilters: [], otherFilters: [], multiListFilters: [] });
    this.handleClearFilterList(quickFilters);
    this.handleClearCustomFilters(customFilters);
    this.handleClearOthersFilters(otherFilters);
    multiListFilters.forEach(multiListFilter => this.handleClearSigleFilter(multiListFilter));
    forceUpdate(this);
  }
  handleClearOthersFilters(otherFilters) {
    this.filters = this.filters.map(filter => otherFilters.includes(filter) ? (Object.assign(Object.assign({}, filter), { value: undefined })) : filter);
  }
  handleClearCustomFilters(customFilters) {
    this.filters.forEach((filter, index) => {
      if (filter.filterType === FilterType.CUSTOM_FILTER)
        this.filters[index] = this.clearAllCustomFilter(customFilters).shift();
    });
  }
  clearAllCustomFilter(filterConfigSnapshot) {
    return filterConfigSnapshot.map(filterItem => {
      const copy = Object.assign({}, filterItem);
      delete copy.value;
      copy.visible = false;
      if (copy.groupedItems) {
        copy.groupedItems = this.clearAllCustomFilter(copy.groupedItems);
      }
      return copy;
    });
  }
  hasChangeToSave() {
    const hasChangesPersonalizedFilters = ObjectUtils.objectToString(this.filters) !== ObjectUtils.objectToString(this.filters);
    return hasChangesPersonalizedFilters;
  }
  handleClose() {
    const hasChangesToSave = this.hasChangeToSave();
    if (!hasChangesToSave) {
      this.closeModal();
      return;
    }
    return ApplicationUtils.confirm(this.getCustomMessage('validations.notSaved.title'), this.getCustomMessage('validations.notSaved.message')).then((cancelAction) => {
      if (cancelAction)
        this.closeModal();
    });
  }
  handleApplyFilters() {
    if (!this.validateFilters()) {
      return;
    }
    const filterPersonalized = this.filters.find(filter => filter.filterType === FilterType.CUSTOM_FILTER || filter.filterType === FilterType.DEFAULT_FILTER);
    if (this.isValidCustomFilter(filterPersonalized)) {
      this.applyFilters(this.filters);
    }
    if (this.filtersToDelete.length > 0) {
      this.filtersToDelete.forEach(filter => {
        this.deletePersonalizedFilter(filter, this.configName);
      });
      this.filtersToDelete = [];
    }
    if (this.filterDefaultToDelete) {
      this.deletePersonalizedFilter(this.filterDefaultToDelete, this.configName, true);
      this._defaultFilter = undefined;
      this.filterDefaultToDelete = undefined;
    }
  }
  isValidCustomFilter(filterPersonalized) {
    const isValid = PersonalizedFilterUtils.validateVariableValues(filterPersonalized);
    if (!isValid) {
      ApplicationUtils.alert(this.getCustomMessage('validations.notFullFilled.title'), this.getCustomMessage('validations.notFullFilled.message'));
      return false;
    }
    return true;
  }
  modalActionListener(evt) {
    const modalAction = evt.detail;
    switch (modalAction) {
      case ModalAction.CANCEL:
        this.handleClearAll();
        break;
      case ModalAction.OK:
        this.handleApplyFilters();
        break;
      case ModalAction.CLOSE:
        this.handleClose();
        break;
    }
  }
  handleFilterChange(event) {
    event.stopPropagation();
    const filterConfig = event.detail;
    let config = this.filters.map(filter => filter.id === filterConfig.id ? filterConfig : filter);
    if (this.filterCustomConfigInterceptor) {
      config = this.filterCustomConfigInterceptor(config);
    }
    this.filters = ObjectUtils.copy(config);
  }
  handleClearFilterList(filterList) {
    this.filters = this.filters.map(filter => filterList.includes(filter) ? (Object.assign(Object.assign({}, filter), { value: undefined })) : filter);
  }
  handleClearSigleFilter(filterItem) {
    if (FilterItemType.MULTI_LIST === filterItem.type) {
      let filterItemCopy = ObjectUtils.copy(filterItem);
      this.uncheckFilterValues(filterItemCopy.value);
      const filterListCopy = ObjectUtils.copy(this.filters);
      const index = filterListCopy.findIndex(item => item.id === filterItem.id);
      filterListCopy.splice(index, 1, filterItemCopy);
      this.filters = ObjectUtils.copy(filterListCopy);
      return;
    }
    if (FilterItemType.CHECK_BOX_LIST === filterItem.type) {
      const filterListCopy = ObjectUtils.copy(this.filters);
      filterListCopy.find(filter => filter.id === filterItem.id).value = undefined;
      this.filters = ObjectUtils.copy(filterListCopy);
      return;
    }
    const filter = this.filters.find(filter => filter.id === filterItem.id);
    filter.value = undefined;
    this.filters = ObjectUtils.copy(this.filters);
  }
  uncheckFilterValues(valueList) {
    valueList.forEach(value => {
      if (!!value) {
        value.check = false;
      }
    });
    return valueList;
  }
  validateFilters() {
    const notValidFilters = getInvalidFilters(this.filters);
    this.filtersWithError = notValidFilters.map(item => item.id);
    if (notValidFilters.length === 0) {
      return true;
    }
    notValidFilters.forEach(item => {
      const filterItem = this._element.querySelector(`#filter-item-${item.id}`);
      if (filterItem) {
        filterItem["errorMessage"] = item.requiredMessage || this.getCustomMessage('validations.requiredFilter');
      }
    });
    return false;
  }
  renderFilterItem(filterItem, fullRow) {
    return (h("snk-filter-modal-item", { key: `modal-item-${filterItem.id}`, class: fullRow ? 'ez-col ez-col--sd-12' : 'ez-col ez-col--sd-6 ez-padding--small', filterItem: filterItem, configName: this.configName, onFilterChange: (event) => this.handleFilterChange(event), onEditPersonalizedFilter: evt => this.editPersonalizedFilter(evt.detail), onAddPersonalizedFilter: () => this.addPersonalizedFilter() }));
  }
  isDefaultFilterNumberVariation(filter) {
    var _a;
    return filter.type === FilterItemType.NUMBER
      && (!filter.props.variation || ((_a = filter.props) === null || _a === void 0 ? void 0 : _a.variation) === FilterNumberVariation.DEFAULT);
  }
  mountFiltersLines(filters) {
    const MAX_LINE_LENGTH = 2;
    let currentLine = 0;
    let forceAddCurrent = false;
    const filtersLines = {};
    for (let curr = 0; curr < filters.length; curr++) {
      filtersLines[currentLine] = filtersLines[currentLine] || [];
      const item = filters[curr];
      const isLast = curr === filters.length - 1;
      const currentItemMatch = item.type === FilterItemType.TEXT || this.isDefaultFilterNumberVariation(item);
      const nextItemMatch = isLast ? false : filters[curr + 1].type === FilterItemType.TEXT || this.isDefaultFilterNumberVariation(filters[curr + 1]);
      if ((currentItemMatch && nextItemMatch) || forceAddCurrent) {
        filtersLines[currentLine].push(item);
        forceAddCurrent = filtersLines[currentLine].length < MAX_LINE_LENGTH;
        if (filtersLines[currentLine].length === MAX_LINE_LENGTH)
          ++currentLine;
        continue;
      }
      filtersLines[currentLine] = filtersLines[currentLine] || [];
      filtersLines[currentLine].push(item);
      ++currentLine;
    }
    return Object.values(filtersLines);
  }
  renderFilterLine(filters) {
    const fullLine = filters.length === 1;
    return filters.map((filter) => this.renderFilterItem(filter, fullLine));
  }
  getIformedFiltersCount(listItems) {
    let countInformedItens = 0;
    listItems.forEach(localItem => {
      var _a, _b, _c, _d, _e, _f, _g, _h;
      const item = this.filterConfig.find(filter => filter.id === localItem.id);
      if (FilterItemType.MULTI_LIST === item.type) {
        countInformedItens += (_e = (_d = (_c = ((_b = (_a = item.value) === null || _a === void 0 ? void 0 : _a.elements) !== null && _b !== void 0 ? _b : item.value)) === null || _c === void 0 ? void 0 : _c.filter(value => value === null || value === void 0 ? void 0 : value.check)) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0;
        return;
      }
      if (FilterItemType.CHECK_BOX_LIST === item.type) {
        countInformedItens += Object.entries((_f = item.value) !== null && _f !== void 0 ? _f : {})
          .filter(([_, value]) => value === true)
          .map(([key, _]) => key).length;
        return;
      }
      if (FilterItemType.PERIOD === item.type) {
        if (!!((_g = item.value) === null || _g === void 0 ? void 0 : _g.start) || !!((_h = item.value) === null || _h === void 0 ? void 0 : _h.end)) {
          countInformedItens++;
        }
        return;
      }
      if (item.groupedItems != undefined) {
        countInformedItens = item.groupedItems.filter(item => item.visible).length;
        return;
      }
      if (!!item.value) {
        countInformedItens++;
      }
    });
    return countInformedItens;
  }
  renderCollapsibleFilterBox(label, listItems, isSingleItem, shouldRenderFooter = true) {
    if (!listItems.length)
      return null;
    const appliedFilters = this.getIformedFiltersCount(listItems);
    const lines = this.mountFiltersLines(listItems);
    const countFiltersWithError = this.filtersWithError.filter(item => listItems.some(filter => filter.id === item)).length;
    return (h("ez-collapsible-box", { class: "snk-filter-modal__collapsible-box", headerSize: "medium", value: true, label: label }, h("div", { class: "ez-flex ez-flex--justify-end grow", slot: "rightSlot" }, !!appliedFilters && (h("ez-badge", { class: "ez-badge--primary-subtle", label: appliedFilters === null || appliedFilters === void 0 ? void 0 : appliedFilters.toString() })), !!countFiltersWithError && (h("ez-badge", { class: "ez-badge--error-subtle", label: countFiltersWithError === null || countFiltersWithError === void 0 ? void 0 : countFiltersWithError.toString() }))), h("div", { class: "ez-row snk-filter-modal__rendered-items" }, lines.map(this.renderFilterLine.bind(this))), shouldRenderFooter && (h("div", { class: "ez-flex ez-flex--justify-end grow" }, h("ez-button", { class: "ez-button--tertiary", size: "medium", label: this.getCustomMessage("clearModal"), onClick: () => isSingleItem ? this.handleClearSigleFilter(listItems[0]) : this.handleClearFilterList(listItems) })))));
  }
  handleDeleteFilter() {
    this._application.confirm(this.getMessage('snkPersonalizedFilter.deleteConfirm.title'), this.getMessage('snkPersonalizedFilter.info.deleteDefaultFilterConfirm'), "alert-circle-inverted", "critical").then((actionConfirmed) => {
      if (!actionConfirmed) {
        return;
      }
      this.filterDefaultToDelete = this._defaultFilter;
      this.filters = this.filters.filter(filter => filter.id !== FilterType.DEFAULT_FILTER);
    });
  }
  handleActionSelectedDefaultFilter({ detail: action }) {
    switch (action) {
      case ActionDefaultFilter.CREATE:
        this.addPersonalizedFilter(true);
        break;
      case ActionDefaultFilter.EDIT:
        this.editPersonalizedFilter(this._defaultFilter.id, true);
        break;
      case ActionDefaultFilter.REMOVE:
        this.handleDeleteFilter();
        break;
    }
  }
  getCustomFilter(filters) {
    const customFilters = filters.filter((filter) => filter.filterType === FilterType.CUSTOM_FILTER);
    return customFilters;
  }
  getDefaultFilter(filters) {
    const defaultFilter = filters.find((item) => item.id === DefaultFilter.id);
    return defaultFilter;
  }
  async componentWillLoad() {
    this._application = ApplicationContext.getContextValue('__SNK__APPLICATION__');
    this._isUserSup = await this._application.isUserSup();
    this.filters = ObjectUtils.copy(this.filterConfig);
  }
  componentWillRender() {
    this._modalTitle = this.getCustomMessage('title');
    this._okButtonLabel = this.getCustomMessage('okButtonLabel');
    this._cancelButtonLabel = this.getCustomMessage('cancelButtonLabel');
  }
  componentDidLoad() {
    this.validateFilters();
  }
  render() {
    this._defaultFilter = this._isUserSup ? this.getDefaultFilter(this.filters) : undefined;
    const customFilters = this.getCustomFilter(this.filters);
    const quickFilters = this.filters.filter(filter => filter.filterType === FilterType.QUICK_FILTER);
    const otherFilters = this.filters.filter(filter => filter.filterType === FilterType.OTHER_FILTERS);
    return (h("ez-modal", { opened: this.opened, modalSize: "col--sd-3", align: "right", heightMode: "full", closeEsc: true }, h("ez-modal-container", { class: "snk-filter-modal__container", modalTitle: this._modalTitle, cancelButtonLabel: this._cancelButtonLabel, okButtonLabel: this._okButtonLabel, onEzModalAction: this.modalActionListener.bind(this) }, h("div", { class: "snk-filter-modal__content ez-col--sd-12" }, this._isUserSup &&
      h("snk-default-filter", { getMessage: this.getCustomMessage.bind(this), hasDefaultFilter: !!this._defaultFilter, onActionSelected: this.handleActionSelectedDefaultFilter.bind(this) }), !this.disablePersonalizedFilter && this.renderCollapsibleFilterBox(this.getCustomMessage('customFilters'), customFilters, false, false), this.renderCollapsibleFilterBox(this.getCustomMessage('quickFilters'), quickFilters, false), otherFilters.map(filter => this.renderCollapsibleFilterBox(filter.label, [filter], true))))));
  }
  get _element() { return this; }
  static get watchers() { return {
    "filterConfig": ["filterConfigChangeHandler"]
  }; }
  static get style() { return snkFilterModalCss; }
}, [0, "snk-filter-modal", {
    "getMessage": [16],
    "configName": [1025, "config-name"],
    "filterConfig": [1040],
    "opened": [4],
    "applyFilters": [16],
    "closeModal": [16],
    "addPersonalizedFilter": [16],
    "editPersonalizedFilter": [16],
    "deletePersonalizedFilter": [16],
    "filtersToDelete": [1040],
    "filterDefaultToDelete": [1040],
    "disablePersonalizedFilter": [4, "disable-personalized-filter"],
    "filterCustomConfigInterceptor": [16],
    "filtersWithError": [32]
  }, [[0, "deleteFilter", "deletePersonalizedFilterListener"]]]);
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-filter-modal", "snk-default-filter", "snk-filter-modal-item"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-filter-modal":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkFilterModal);
      }
      break;
    case "snk-default-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
    case "snk-filter-modal-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$1();
      }
      break;
  } });
}

export { SnkFilterModal as S, defineCustomElement as d, validateFilters as v };
