import { Search } from '@wix/design-system';
import React, { useEffect, useRef } from 'react';
import { observer } from 'mobx-react-lite';
import { CustomColumnsState } from '../../state';
import { FiltersMap } from '@wix/bex-core';
import { useWixPatternsContainer } from '@wix/bex-core/react';

export interface CustomColumnsSearchProps<T, F extends FiltersMap> {
  state: CustomColumnsState<T, F>;
}

export function _CustomColumnsSearch<T, F extends FiltersMap>({
  state,
}: CustomColumnsSearchProps<T, F>) {
  const { translate: t } = useWixPatternsContainer();
  const searchInputRef = useRef<Search>(null);

  useEffect(() => {
    state.columnsCollection.searchInputRef = {
      focus: () => {
        searchInputRef.current?.focus();
      },
    };
    return () => {
      state.columnsCollection.searchInputRef = null;
    };
  }, [state.columnsCollection]);

  return (
    <Search
      ref={searchInputRef}
      dataHook="custom-columns-search"
      size="small"
      value={state.searchValue}
      onChange={(e) => {
        state.setSearchValue(e.target.value);
      }}
      onClear={() => {
        state.setSearchValue('');
      }}
      placeholder={t(
        'cairo.table.custom-columns.dragAndDrop.search-placeholder',
      )}
    />
  );
}

export const CustomColumnsSearch = observer(_CustomColumnsSearch);
