import React, { useMemo, useRef } from 'react';
import { observer } from 'mobx-react-lite';
import { Box, Input, Loader, } from '@wix/design-system';
import { ViewsDropdownModals } from './ViewsDropdownModals';
import { classes, st } from './ViewsDropdown.st.css.js';
import { ManageViewPopover, } from './ManageViewPopover';
import { buildCategoryOption, buildViewOption, getCategoryName, getViewName, } from './viewsDropdownRenderHelpers';
import { AutoCompleteReadonly } from './AutoCompleteReadonly';
import { SaveToNewViewFooter } from './SaveToNewViewFooter';
import { ViewsDropdownPrefix } from './ViewsDropdownPrefix';
import { useWixPatternsContainer } from '../..';
export const VIEWS_REDESIGN_EXPERIMENT = 'specs.cairo.ViewsRedesign';
function _ViewsDropdown({ onSelect, dataHook, state, showTotal = true, dropdownWidth = '200px', ...dropdownProps }) {
    const container = useWixPatternsContainer();
    const isRedesign = container.internalExperiments?.enabled(VIEWS_REDESIGN_EXPERIMENT);
    const { views: viewsState } = state;
    const { currentView, collection, localSearchState } = viewsState;
    const { filteredCategoriesWithViews } = localSearchState;
    const { translate: t } = collection;
    const showLoader = collection.result.status.isIdle || collection.result.status.isLoading;
    const manageViewRef = useRef(null);
    const viewsOptions = useMemo(() => {
        const { viewsWithoutCategory, categories } = filteredCategoriesWithViews;
        const buildOption = (view) => {
            const isSelected = currentView?.id === view.id;
            const option = buildViewOption({
                view,
                viewsState,
                suffix: isRedesign && isSelected ? (React.createElement(ManageViewPopover, { ref: manageViewRef, origin: "MainToolbar", state: state, redesign: true })) : undefined,
            });
            return option;
        };
        return [
            ...viewsWithoutCategory.map(buildOption),
            ...categories.flatMap((category) => [
                ...(getCategoryName({ category, viewsState })
                    ? [buildCategoryOption({ category, viewsState })]
                    : []),
                ...category.views.map(buildOption),
            ]),
        ];
    }, [
        filteredCategoriesWithViews,
        container.initTask.status,
        currentView?.id,
        isRedesign,
    ]);
    const { options, fixedFooter } = showLoader
        ? {
            options: [],
            fixedFooter: (React.createElement(Box, { dataHook: "initial-loader", width: "100%", align: "center", verticalAlign: "middle", padding: "SP2" },
                React.createElement(Loader, { size: "small" }))),
        }
        : {
            options: viewsOptions,
            fixedFooter: isRedesign ? (React.createElement(SaveToNewViewFooter, { state: state })) : undefined,
        };
    const { table: { collection: mainCollection }, } = state;
    const shouldShowTotal = showTotal &&
        (mainCollection.totalStatus === 'success' ||
            mainCollection.showRefreshLoader);
    return (React.createElement(Box, { dataHook: dataHook },
        React.createElement(Box, { width: dropdownWidth, direction: "vertical" },
            React.createElement(AutoCompleteReadonly, { emptyStateMessage: !showLoader && t('cairo.viewsDropdown.nothingMatches.text'), state: state.views.autoCompleteReadonlyState, value: localSearchState.inputValue, onChange: (e) => localSearchState.setInputValueAndScheduleSearch(e.target.value), clearInput: () => localSearchState.clearSearch(), dropdownWidth: isRedesign ? '264px' : dropdownWidth, popoverProps: { placement: 'bottom-start' }, ...dropdownProps, onDrillIn: isRedesign
                    ? (option) => {
                        if (option.id === currentView?.id) {
                            manageViewRef.current?.focusTrigger();
                        }
                    }
                    : undefined, onInputClicked: (e) => {
                    state.viewsStateBIReporter.clickOnViewDropdownBI();
                    dropdownProps?.onInputClicked?.(e);
                }, fixedFooter: fixedFooter, border: "round", selectedId: currentView?.id, selectedLabel: currentView
                    ? getViewName({ view: currentView, viewsState })
                    : undefined, textOverflow: "ellipsis", prefix: React.createElement("div", { "data-hook": "views-dropdown-prefix", onClick: () => viewsState.autoCompleteReadonlyState.focusInput(), style: { cursor: 'pointer', display: 'inline-flex' } },
                    React.createElement(ViewsDropdownPrefix, { state: state })), suffix: shouldShowTotal ? (React.createElement("div", { "data-hook": "views-dropdown-suffix", onClick: () => viewsState.autoCompleteReadonlyState.focusInput(), style: { cursor: 'pointer', display: 'inline-flex' } },
                    React.createElement(Box, { className: "total-count" },
                        React.createElement(Input.Affix, null,
                            "(",
                            state.table.collection.result.total,
                            ")")))) : undefined, className: st(classes.root), dataHook: "collection-views-dropdown", onSelect: (option) => {
                    viewsState.events.emit('beforeSelectView');
                    const id = option.id.toString();
                    const view = viewsState.getView(id);
                    if (view) {
                        onSelect?.(view);
                        viewsState.selectView({ id });
                        viewsState.events.emit('afterSelectView', { view });
                    }
                    localSearchState.clearSearch();
                }, options: options, placeholder: t('cairo.viewDropdown.unsavedView.status') })),
        !isRedesign && (React.createElement(Box, { verticalAlign: "middle", paddingLeft: "SP2" },
            React.createElement(ManageViewPopover, { origin: "MainToolbar", state: state }))),
        React.createElement(ViewsDropdownModals, { state: state })));
}
export const ViewsDropdown = observer(_ViewsDropdown);
//# sourceMappingURL=ViewsDropdown.js.map