import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { MultiSelect, Box, TextButton, listItemActionBuilder, Divider, ListItemAction, Tag, Text, } from '@wix/design-system';
import { Add as AddIcon } from '@wix/wix-ui-icons-common';
import { runInAction } from 'mobx';
import { ADD_ITEM_OPTION_ID, MANAGE_TAGS_OPTION_ID, TAG_MAX_LENGTH, TagsFormState, } from '@wix/bex-core';
import { TagsModalState } from '../../state/TagsModalState';
import { useSelector } from '../../useSelector';
const ReadonlyTagsWidgetContent = ({ formState, }) => {
    const { translate: t, initTask } = useWixPatternsContainer();
    useSelector(() => initTask.status);
    if (formState.displayedAssignedTags.length === 0) {
        return (React.createElement(Text, { dataHook: "tags-widget-readonly-empty-state" }, t('cairo.tags.tagsField.readOnly.emptyState')));
    }
    return (React.createElement(Box, { gap: "tiny" }, formState.displayedAssignedTags.map((tag) => (React.createElement(Tag, { key: tag.id, id: tag.id, dataHook: "tags-widget-tag", removable: false }, tag.label)))));
};
const ManageTagsModal = React.lazy(() => import(
/* webpackChunkName: "ManageTagsModal" */ '../Tags/ManageTags/ManageTagsModal/ManageTagsModal').then((module) => ({ default: module.ManageTagsModal })));
const _TagsWidgetContent = ({ state, onSubmit, entityTypeName, initialTags, entityId, readOnly, popoverProps, manageTagsShowUndoToast, }) => {
    const { translate: t } = useWixPatternsContainer();
    const [formState] = useState(() => runInAction(() => (state.tagsFormState ??= new TagsFormState({
        initialTags,
        tagsManagementState: state.tagsManagementState,
        origin: state.origin,
        entityTypeName,
    }))));
    const [tagsModalState] = useState(() => new TagsModalState({
        tagsManagementState: state.tagsManagementState,
        entityTypeName,
        showUndoToast: manageTagsShowUndoToast,
    }));
    useEffect(() => {
        const disposers = [formState.init({ entityId }), tagsModalState.init()];
        return () => {
            disposers.forEach((disposer) => disposer());
        };
    }, []);
    const initialTagIdsKey = (initialTags?.privateTags?.tagIds ?? []).join(',');
    useEffect(() => {
        formState.tagsAssignmentState.replaceAssigned(initialTags?.privateTags?.tagIds ?? []);
    }, [initialTagIdsKey]);
    const { shouldAllowTagsPagination } = formState.tagsManagementState;
    const tagsOptions = useMemo(() => {
        const options = formState.displayedTagOptions;
        const addTagOptionItems = formState.shouldShowCreateTagOption
            ? [
                listItemActionBuilder({
                    id: ADD_ITEM_OPTION_ID,
                    title: t('cairo.tags.tagsWidget.options.add.CTA', {
                        tagName: formState.searchValue?.slice(0, TAG_MAX_LENGTH),
                    }),
                    prefixIcon: React.createElement(AddIcon, null),
                }),
            ]
            : [];
        return [...addTagOptionItems, ...options];
    }, [
        formState.displayedTagOptions,
        formState.searchValue,
        formState.shouldShowCreateTagOption,
        formState.displayedAssignedTags,
    ]);
    const handleSearchChange = useCallback((event) => {
        formState.handleSearchChange(event.target.value);
    }, []);
    const handleTagSelect = useCallback(async (option) => {
        const convertedOption = {
            id: option.id,
            value: option.value,
        };
        formState.handleTagSelect(convertedOption, onSubmit);
    }, [onSubmit]);
    const handleTagRemove = useCallback((tagId) => {
        formState.unassignTag(tagId, onSubmit);
    }, [onSubmit]);
    const handleOptionsShow = useCallback(() => {
        formState.handleOptionsShow();
    }, []);
    const handleManageTagsCtaClick = useCallback(() => {
        formState.handleManageTagsCtaClick();
        tagsModalState.openManageTagsModal({
            origin: formState.origin,
            tagSubOrigin: 'tagsWidget',
        });
    }, []);
    const handleMultiSelectFocus = useCallback(() => {
        formState.setIsMultiSelectOnFocus(true);
    }, []);
    const handleMultiSelectBlur = useCallback(() => {
        formState.setIsMultiSelectOnFocus(false);
    }, []);
    if (readOnly) {
        return React.createElement(ReadonlyTagsWidgetContent, { formState: formState });
    }
    return (React.createElement(React.Fragment, null,
        React.createElement(MultiSelect, { popoverProps: popoverProps, ...(shouldAllowTagsPagination
                ? {
                    infiniteScroll: true,
                    hasMore: formState.tagsManagementState.hasMore,
                    loadMore: () => formState.tagsManagementState.loadMore(),
                }
                : {}), value: formState.searchValue, onChange: handleSearchChange, options: tagsOptions, onFocus: handleMultiSelectFocus, onBlur: handleMultiSelectBlur, tags: formState.displayedAssignedTags, onOptionsShow: handleOptionsShow, markedOption: formState.shouldShowCreateTagOption ? ADD_ITEM_OPTION_ID : true, customSuffix: React.createElement(Box, null,
                React.createElement(TextButton, { size: "small", prefixIcon: React.createElement(AddIcon, null), dataHook: "assign-tags-cta" }, t('cairo.tags.tagsWidget.add.CTA'))), fixedFooter: formState.isInEmptyState ? undefined : (React.createElement("div", null,
                !!tagsOptions.length && React.createElement(Divider, null),
                React.createElement(ListItemAction, { dataHook: "manage-tags-cta", onClick: handleManageTagsCtaClick, id: MANAGE_TAGS_OPTION_ID, title: t('cairo.tags.tagsWidget.options.manage.CTA') }))), onSelect: handleTagSelect, onRemoveTag: handleTagRemove, placeholder: formState.isInEmptyState && formState.isMultiSelectOnFocus
                ? t('cairo.tags.tagsWidget.input.placeholder')
                : undefined, dataHook: "tags-widget-multi-select" }),
        React.createElement(React.Suspense, { fallback: null },
            React.createElement(ManageTagsModal, { state: tagsModalState }))));
};
export const TagsWidgetContent = observer(_TagsWidgetContent);
//# sourceMappingURL=TagsWidgetContent.js.map