import { observer } from 'mobx-react-lite';
import { Search, SearchProps } from '@wix/design-system';
import React, { CSSProperties } from 'react';
import { FiltersMap } from '@wix/bex-core';
import { useCollectionContext } from '@wix/bex-core/react';

export interface CollectionSearchProps extends Partial<SearchProps> {
  onSearchChange?: (value: string) => unknown;
  onSearchClick?: () => unknown;
  onSearchBlur?: (value: string) => unknown;
  visibility?: CSSProperties['visibility'];
}

export const CollectionSearch = observer(function CollectionSearch<
  T,
  F extends FiltersMap = FiltersMap,
>({
  onSearchChange,
  onSearchClick,
  onSearchBlur,
  visibility,
  ...rest
}: CollectionSearchProps) {
  const collection = useCollectionContext<T, F>();
  const {
    query: { search },
    translate: t,
  } = collection;

  return (
    <Search
      dataHook="collection-search"
      onChange={(e) => {
        const value = e.target.value;
        collection.search(e.target.value, { clearResult: true });
        onSearchChange?.(value);
      }}
      value={search.value}
      onClear={() => {
        const value = '';
        collection.clearSearch();
        onSearchChange?.(value);
      }}
      placeholder={t('cairo.searchPlaceholder', { defaultValue: '' })}
      onInputClicked={() => onSearchClick?.()}
      textOverflow="ellipsis"
      onBlur={(e) => {
        const value = e.target.value;
        onSearchBlur?.(value);
      }}
      {...rest}
    />
  );
});
