import { observer } from 'mobx-react-lite';
import { Box, Search, TextButton } from '@wix/design-system';
import React, { useState, useRef, useCallback, useEffect, } from 'react';
import { useCollectionContext } from '@wix/bex-core/react';
import { useIsMobile } from '../hooks/useIsMobile';
export const CollectionSearch = observer(function CollectionSearch({ onSearchChange, onSearchClick, onSearchBlur, visibility, expandable, ...rest }) {
    const collection = useCollectionContext();
    const { query: { search }, translate: t, } = collection;
    const isMobile = useIsMobile();
    const [isSearchExpanded, setIsSearchExpanded] = useState(!!search.value);
    const searchInputRef = useRef(null);
    useEffect(() => {
        collection.searchInputRef = {
            focus: () => {
                searchInputRef.current?.focus();
            },
        };
        return () => {
            collection.searchInputRef = null;
        };
    }, [collection]);
    const handleCancel = useCallback(() => {
        collection.clearSearch();
        onSearchChange?.('');
        if (searchInputRef.current) {
            searchInputRef.current.blur();
            setIsSearchExpanded(false);
        }
    }, [collection, onSearchChange]);
    const showCancelButton = isMobile && isSearchExpanded;
    const searchElement = (React.createElement(Search, { dataHook: "collection-search", onChange: (e) => {
            const value = e.target.value;
            collection.search(e.target.value, { clearResult: true });
            onSearchChange?.(value);
        }, ref: searchInputRef, value: search.value, onClear: () => {
            const value = '';
            collection.clearSearch();
            onSearchChange?.(value);
        }, expandable: expandable, expandDirection: isMobile ? 'left' : undefined, placeholder: t('cairo.searchPlaceholder', { defaultValue: '' }), textOverflow: "ellipsis", onFocus: () => {
            setIsSearchExpanded(true);
        }, onBlur: (e) => {
            const value = e.target.value;
            if (!value) {
                setIsSearchExpanded(false);
            }
            onSearchBlur?.(value);
        }, ...rest }));
    if (isMobile && expandable) {
        return (React.createElement(Box, { width: "100%", gap: "SP2", verticalAlign: "middle" },
            searchElement,
            showCancelButton && (React.createElement(TextButton, { dataHook: "collection-search-cancel", onClick: handleCancel, size: "small" }, t('cairo.cancel.button')))));
    }
    return searchElement;
});
//# sourceMappingURL=CollectionSearch.js.map