import { action, makeObservable, observable } from 'mobx';
import { ConditionalModalState, TAG_MAX_LENGTH, TagsBIReporter, TagsSearchState, } from '@wix/bex-core';
import { cairoTagsModalStartLoad } from '@wix/bex-core/bi';
import { addEventListener } from '@wix/bex-core/util';
const actionOrigin = 'Manage Tags Modal';
export class TagsModalState {
    constructor({ tagsManagementState, entityTypeName, showUndoToast = true, }) {
        this.manageTagsModalState = new ConditionalModalState();
        this.confirmModalState = new ConditionalModalState();
        this.origin = undefined;
        this.tagSubOrigin = undefined;
        this.editedTagId = null;
        this.editedTagErrorMessage = null;
        this.isShowingNewTagListItem = false;
        this.toastConfigs = observable.array([], {
            deep: false,
        });
        this.ref = null;
        this.tagsManagementState = tagsManagementState;
        this.tagsSearchState = new TagsSearchState({
            tagsManagementState,
        });
        this.entityTypeName = entityTypeName;
        this.showUndoToast = showUndoToast;
        this.container = tagsManagementState.container;
        this.tagsBIReporter = new TagsBIReporter({
            collection: this.tagsManagementState.collection,
            reportBi: this.tagsManagementState.container.createBILogger({
                componentType: 'ManageTagsModal',
                ...tagsManagementState.fqdn,
            }),
            location: 'Manage tags modal',
        });
        makeObservable(this, {
            editedTagId: observable,
            editedTagErrorMessage: observable,
            isShowingNewTagListItem: observable,
            init: action,
            openManageTagsModal: action,
            closeManageTagsModal: action,
            handleSearchChange: action,
            handleSearchClear: action,
            handleCreateCtaClick: action,
            handleEditCtaClick: action,
            handleCancelEditCtaClick: action,
            openConfirmDeleteModal: action,
            createTagFromSearch: action,
            createTagFromList: action,
            updateTag: action,
            deleteTag: action,
            showNotification: action,
            hideNotification: action,
        });
    }
    init() {
        const disposers = [
            addEventListener(this.tagsManagementState.events, 'showToast', (toastConfig) => {
                this.showNotification(toastConfig);
            }),
            addEventListener(this.tagsManagementState.events, 'hideToast', (toastConfig) => {
                this.hideNotification(toastConfig);
            }),
            () => {
                window.clearTimeout(this.handleCreateCtaTimeout);
                window.clearTimeout(this.showNotificationTimeout);
                window.clearTimeout(this.createTagFromListTimeout);
                window.clearTimeout(this.updateTagTimeout);
            },
        ];
        return () => {
            disposers.forEach((d) => d?.());
        };
    }
    openManageTagsModal({ origin, tagSubOrigin, }) {
        this.origin = origin;
        this.tagSubOrigin = tagSubOrigin;
        this.manageTagsModalState.modal.open();
        this._reportBiModalOpened();
        this.tagsManagementState.overrideShowToast = true;
    }
    closeManageTagsModal() {
        this.editedTagId = null;
        this.editedTagErrorMessage = null;
        this.isShowingNewTagListItem = false;
        this.tagsSearchState.setSearchValue('');
        this._reportSearchEventsBi('blur');
        this.manageTagsModalState.modal.close();
        this._reportModalClosedBi();
        this.origin = undefined;
        this.tagsManagementState.overrideShowToast = false;
        this.hideNotification();
    }
    openConfirmDeleteModal(props) {
        this.confirmModalState.open({
            theme: 'destructive',
            primaryButtonText: this.container.translate('cairo.tags.manageTags.modal.deleteModal.delete.CTA'),
            secondaryButtonText: this.container.translate('cairo.tags.manageTags.modal.deleteModal.cancel.CTA'),
            title: this.container.translate('cairo.tags.manageTags.modal.deleteModal.title'),
            ...props,
        });
    }
    handleSearchChange(newSearchValue) {
        this.editedTagId = null;
        this.isShowingNewTagListItem = false;
        this._reportSearchChangedBi(newSearchValue);
        this.tagsSearchState.setSearchValue(newSearchValue);
    }
    handleSearchClear() {
        this._reportSearchEventsBi('clear');
        this.tagsSearchState.setSearchValue('');
    }
    handleCreateCtaClick() {
        this.tagsSearchState.setSearchValue('');
        this.editedTagId = null;
        this.isShowingNewTagListItem = true;
        this.handleCreateCtaTimeout = window.setTimeout(() => this._scrollContentTo('bottom'), 100);
    }
    handleEditCtaClick(tag) {
        this._reportSearchEventsBi('select');
        this.editedTagId = tag.id;
    }
    handleCancelEditCtaClick() {
        this.editedTagId = null;
        this.isShowingNewTagListItem = false;
    }
    showNotification(toastConfig) {
        this.toastConfigs.push(toastConfig);
        this.showNotificationTimeout = window.setTimeout(() => {
            this.hideNotification(toastConfig);
        }, 6000);
    }
    hideNotification(toastConfig) {
        if (toastConfig) {
            this.toastConfigs.remove(toastConfig);
        }
        else {
            this.toastConfigs.clear();
        }
    }
    async createTagFromSearch() {
        if (!this.searchValue || this.shownItems.length) {
            return;
        }
        const newName = this.searchValue.slice(0, TAG_MAX_LENGTH);
        this._reportSearchEventsBi('add');
        this._createTag({
            name: newName,
            isFromSearch: true,
            onSuccess: () => this._scrollContentTo('bottom'),
        });
        this.tagsSearchState.setSearchValue('');
    }
    async createTagFromList(newName) {
        const { status, statusMessage } = this._isValidName(newName);
        if (status === 'error') {
            this.editedTagErrorMessage = statusMessage;
            this.createTagFromListTimeout = window.setTimeout(() => this._scrollContentTo('bottom'), 100);
            return;
        }
        this._createTag({
            name: newName,
        });
        this.isShowingNewTagListItem = false;
    }
    async updateTag({ tag, newName, isLastTag, }) {
        if (newName === tag.name) {
            this.editedTagId = null;
            return;
        }
        const { status, statusMessage } = this._isValidName(newName);
        if (status === 'error') {
            this.editedTagErrorMessage = statusMessage;
            if (isLastTag) {
                this.updateTagTimeout = window.setTimeout(() => this._scrollContentTo('bottom'), 100);
            }
            return;
        }
        this.editedTagId = null;
        const previousName = tag.name;
        const isFromSearch = this.tagsSearchState.searchValue !== '';
        this.tagsManagementState.updateTag({
            tagToUpdate: { ...tag, name: newName },
            previousName,
            isFromSearch,
            filteredListSize: this.shownItems.length,
            origin: actionOrigin,
            tagSubOrigin: this.tagSubOrigin,
            tagsBIReporter: this.tagsBIReporter,
            optimisticActionParams: {
                keepPosition: true,
                successToast: {
                    biName: 'cairo-save-rename-tag-success',
                    message: this.container.translate('cairo.tags.manageTags.modal.toast.rename.success'),
                },
                showUndoToast: this.showUndoToast,
                errorToast: (error) => {
                    const resolvedError = this.container.errorHandler.getResolvedError?.(error);
                    return {
                        biName: 'cairo-save-rename-tag-error',
                        message: resolvedError?.message ??
                            this.container.translate('cairo.tags.manageTags.modal.toast.rename.error'),
                        type: 'ERROR',
                    };
                },
            },
        });
    }
    async deleteTag(tagToDelete) {
        this._reportSearchEventsBi('select');
        this.tagToDelete = tagToDelete;
        const isFromSearch = this.tagsSearchState.searchValue !== '';
        this.openConfirmDeleteModal({
            primaryButtonOnClick: async () => {
                this.tagsManagementState.deleteTag({
                    tagToDelete,
                    isFromSearch,
                    filteredListSize: this.shownItems.length,
                    origin: actionOrigin,
                    tagSubOrigin: this.tagSubOrigin,
                    tagsBIReporter: this.tagsBIReporter,
                    optimisticActionParams: {
                        successToast: {
                            biName: 'cairo-delete-tag-success',
                            message: this.container.translate('cairo.tags.manageTags.modal.toast.delete.success'),
                        },
                        showUndoToast: this.showUndoToast,
                        errorToast: (error) => {
                            const resolvedError = this.container.errorHandler.getResolvedError?.(error);
                            return {
                                biName: 'cairo-delete-tag-error',
                                message: resolvedError?.message ??
                                    'cairo.tags.manageTags.modal.toast.delete.error',
                                type: 'ERROR',
                            };
                        },
                    },
                });
            },
        });
    }
    get searchValue() {
        return this.tagsSearchState.searchValue;
    }
    get shownItems() {
        return [...this.tagsSearchState.items].sort((tag1, tag2) => new Date(tag1.createdDate).valueOf() -
            new Date(tag2.createdDate).valueOf());
    }
    get isOpen() {
        return this.manageTagsModalState.isOpen;
    }
    get toastConfig() {
        return this.toastConfigs[this.toastConfigs.length - 1] ?? null;
    }
    async _createTag({ name, isFromSearch = false, onSuccess, }) {
        this.tagsManagementState.createTag({
            name,
            isFromSearch,
            filteredListSize: this.shownItems.length,
            onSuccess,
            origin: actionOrigin,
            tagSubOrigin: this.tagSubOrigin,
            tagsBIReporter: this.tagsBIReporter,
            visualType: 'notification',
            optimisticActionParams: {
                successToast: {
                    biName: 'cairo-save-new-tag-success',
                    message: this.container.translate('cairo.tags.manageTags.modal.toast.create.success'),
                },
                errorToast: (error) => {
                    const resolvedError = this.container.errorHandler.getResolvedError?.(error);
                    return {
                        biName: 'cairo-save-new-tag-error',
                        message: resolvedError?.message ??
                            this.container.translate('cairo.tags.manageTags.modal.toast.create.error'),
                        action: resolvedError?.action,
                    };
                },
            },
        });
        this.editedTagErrorMessage = null;
    }
    _isValidName(tagName) {
        if (tagName.length === 0) {
            return this._getValidationMessage(this.container.translate('cairo.tags.manageTags.modal.list.input.validation.emptyName'));
        }
        if (tagName.length > TAG_MAX_LENGTH) {
            return this._getValidationMessage(this.container.translate('cairo.tags.manageTags.modal.list.input.validation.maxLength', { count: TAG_MAX_LENGTH }));
        }
        if (this.tagsManagementState.items.find(({ name }) => name.toLowerCase() === tagName.toLowerCase())) {
            return this._getValidationMessage(this.container.translate('cairo.tags.manageTags.modal.list.input.validation.exists'));
        }
        return { status: '', statusMessage: '' };
    }
    _reportBiModalOpened() {
        this.tagsBIReporter.reportBi(cairoTagsModalStartLoad({
            numTags: this.tagsManagementState.items?.length,
            origin: this.origin,
        }));
    }
    _reportModalClosedBi() {
        this.tagsBIReporter.onModalClose({ origin: this.origin });
    }
    _reportSearchChangedBi(searchValue) {
        if (searchValue !== '') {
            this.tagsBIReporter.onSearch(searchValue);
        }
        else {
            this.tagsBIReporter._clearAllEvents();
        }
    }
    _reportSearchEventsBi(event) {
        return this.tagsBIReporter.events.emit(event);
    }
    _scrollContentTo(direction = 'top') {
        this.ref?.current?.scrollTo({
            top: direction === 'top' ? 0 : this.ref?.current?.scrollHeight,
            behavior: 'smooth',
        });
    }
    _getValidationMessage(statusMessage) {
        return {
            status: 'error',
            statusMessage,
        };
    }
}
//# sourceMappingURL=TagsModalState.js.map