import { action, computed, makeObservable, observable } from 'mobx';
import { cairoTagsWidgetClickOnCta, cairoTagsWidgetLoaded, } from '@wix/bex-utils/@wix/bi-logger-os-data/v2';
import { TAG_MAX_LENGTH } from './TagsManagementState';
import { TagsSearchState } from './TagsSearchState';
import { TagsAssignmentState, } from './TagsAssignmentState';
import { TagsBIReporter } from './TagsBIReporter';
export const ADD_ITEM_OPTION_ID = 'add-item-option';
export const MANAGE_TAGS_OPTION_ID = 'manage-tags-option';
export class TagsFormState {
    constructor({ tagsManagementState, origin, initialTags, }) {
        this.previousSearchValue = '';
        this.isMultiSelectOnFocus = false;
        this.assignOptimisticActionParams = (tagName) => ({
            onError: (error) => {
                this.tagsBIReporter.onError({
                    tagName,
                    actionName: 'Assign tag',
                    origin: this.origin,
                }, error);
            },
            errorToast: () => {
                return {
                    biName: 'cairo-assign-tag-error',
                    message: this.container.translate('cairo.tags.collectionPage.toast.update.error'),
                };
            },
            onTryAgain: () => {
                this.tagsBIReporter.onTryAgain({
                    actionName: 'Assign tag',
                });
            },
        });
        this.assignTag = async (tag, onSubmit) => {
            this.tagsAssignmentState.assignTag({
                tag,
                onSubmit,
                isFromSearch: this.previousSearchValue !== '',
                optimisticActionParams: this.assignOptimisticActionParams(tag.name),
            });
        };
        this.unassignTag = async (tagId, onSubmit) => {
            const tagToUnassign = this.tagsAssignmentState.assignedTags.find((tag) => tag.id === tagId);
            if (tagToUnassign) {
                this.tagsAssignmentState.unassignTag({
                    tag: tagToUnassign,
                    onSubmit,
                    isFromSearch: false,
                    optimisticActionParams: {
                        errorToast: () => {
                            return {
                                biName: 'cairo-remove-assign-tag-error',
                                message: this.container.translate('cairo.tags.collectionPage.toast.update.error'),
                            };
                        },
                        onError: (error) => {
                            this.tagsBIReporter.onError({
                                tagName: tagToUnassign.name,
                                actionName: 'Remove assign tag',
                                origin: this.origin,
                            }, error);
                        },
                        onTryAgain: () => {
                            this.tagsBIReporter.onTryAgain({
                                actionName: 'Remove assign tag',
                            });
                        },
                    },
                });
            }
        };
        this.createAndAssignTag = async (name, onSubmit) => {
            this.tagsAssignmentState.createAndAssignTag({
                name,
                onSubmit,
                filteredListSize: this.displayedTagOptions.length,
                createOptimisticActionParams: {
                    errorToast: (error) => {
                        const resolvedError = this.container.errorHandler.getResolvedError?.(error);
                        return {
                            biName: 'cairo-save-new-tag-error',
                            message: resolvedError?.message ??
                                this.container.translate('cairo.tags.collectionPage.toast.create.error'),
                            action: resolvedError?.action,
                        };
                    },
                },
                assignOptimisticActionParams: this.assignOptimisticActionParams(name),
            });
        };
        this.validate = async () => {
            const tags = {
                privateTags: { tagIds: this.tagsAssignmentState.assignedTagIds },
            };
            return {
                isValid: true,
                tags,
                values: tags,
            };
        };
        this.container = tagsManagementState.container;
        this.origin = origin;
        this.tagsManagementState = tagsManagementState;
        this.tagsBIReporter = new TagsBIReporter({
            collection: this.tagsManagementState.collection,
            reportBi: this.container.createBILogger({
                componentType: 'TagsWidget',
                ...tagsManagementState.fqdn,
            }),
            location: 'Tags widget',
        });
        this.tagsAssignmentState = new TagsAssignmentState({
            initialTags,
            tagsManagementState: this.tagsManagementState,
            tagsBIReporter: this.tagsBIReporter,
            origin,
            fqdn: tagsManagementState.fqdn,
        });
        this.tagsSearchState = new TagsSearchState({
            tagsManagementState: this.tagsManagementState,
        });
        makeObservable(this, {
            init: action,
            previousSearchValue: observable,
            isMultiSelectOnFocus: observable,
            displayedAssignedTags: computed,
            displayedTagOptions: computed,
            isDirty: computed,
            handleManageTagsCtaClick: action,
            handleSearchChange: action,
            handleOptionsShow: action,
            setIsMultiSelectOnFocus: action,
        });
    }
    init({ entityId }) {
        this.entityId = entityId;
        const disposers = [
            this.tagsAssignmentState.init({
                entityId,
            }),
        ];
        this.tagsBIReporter.reportBi(cairoTagsWidgetLoaded({
            itemId: this.entityId ?? undefined,
            numTags: this.tagsManagementState.items.length,
            numTagsAssigned: this.tagsAssignmentState.initialTagIds.length,
        }));
        return () => {
            disposers.forEach((disposer) => disposer?.());
        };
    }
    get displayedAssignedTags() {
        return this.tagsAssignmentState.assignedTags.map((assignedTag) => ({
            id: assignedTag.id,
            label: assignedTag.name,
        }));
    }
    get displayedTagOptions() {
        return this.tagsSearchState.items
            .filter((tag) => !this.displayedAssignedTags.find((assignedTag) => assignedTag.label === tag.name))
            .map((tag) => {
            return { id: tag.id, value: tag.name };
        });
    }
    get isInEmptyState() {
        return this.tagsManagementState.items.length === 0;
    }
    get searchValue() {
        return this.tagsSearchState.searchValue;
    }
    get shouldShowCreateTagOption() {
        return this.searchValue && !this.tagsSearchState.hasSameTagAsSearch;
    }
    handleTagSelect(option, onSubmit) {
        if (option.id === ADD_ITEM_OPTION_ID) {
            this._invokeBiOnCtaClick('Create tags');
            const tagName = this.previousSearchValue.slice(0, TAG_MAX_LENGTH);
            this.createAndAssignTag(tagName, onSubmit);
            return;
        }
        this.assignTag({ id: option.id, name: option.value }, onSubmit);
    }
    handleManageTagsCtaClick() {
        this._invokeBiOnCtaClick('Manage tags');
    }
    handleSearchChange(newSearchValue) {
        this.previousSearchValue = this.searchValue;
        this.tagsSearchState.setSearchValue(newSearchValue);
    }
    handleOptionsShow() {
        this._invokeBiOnCtaClick('Assign tags');
    }
    setIsMultiSelectOnFocus(isOnFocusValue) {
        this.isMultiSelectOnFocus = isOnFocusValue;
    }
    get isDirty() {
        return this.tagsAssignmentState.isDirty;
    }
    _invokeBiOnCtaClick(actionName) {
        return this.tagsBIReporter.reportBi(cairoTagsWidgetClickOnCta({
            itemId: this.entityId ?? undefined,
            numTags: this.tagsManagementState.items.length,
            numTagsAssigned: this.tagsAssignmentState.assignedTags.length,
            actionName,
        }));
    }
}
//# sourceMappingURL=TagsFormState.js.map