import { useCallback } from 'react';

import { FieldPrefixIcon } from '../../components/FieldPrefixIcon/FieldPrefixIcon';
import { FieldSuffixIconButton } from '../../components/FieldSuffixIconButton/FieldSuffixIconButton';
import { IconGlyph } from '../../components/Icon/constants';
import { useTranslation } from '../../core/hooks/useTranslation';
import { assertEmptyObject } from '../../utils/assertEmptyObject';
import { BaseTextField, BaseTextFieldProps } from '../BaseTextField/BaseTextField';
import { BaseTextFieldType } from '../BaseTextField/constants';

/** Props for {@link SearchField} */
export interface SearchFieldProps extends Omit<BaseTextFieldProps<string>, 'prefix' | 'suffix' | 'type'> {}

/**
 * Special text field that should be used for search something.
 *
 * ```tsx
 * import { SearchField } from 'ui-kit';
 *
 * <SearchField value="any text" onChange={console.log} />
 * ```
 */
export function SearchField(props: SearchFieldProps) {
  const {
    onChange,
    onBlur,
    placeholder,
    disabled,
    ariaErrorMessage,
    ariaDescribedBy,
    ariaLabel,
    ariaInvalid,
    className,
    id,
    value,
    testId,
    ariaRequired,
    required,
    ...rest
  } = props;
  assertEmptyObject(rest);

  const { t } = useTranslation();

  const handleClearClick = useCallback(() => {
    onChange?.('');
  }, [onChange]);

  return (
    <BaseTextField
      ariaDescribedBy={ariaDescribedBy}
      ariaErrorMessage={ariaErrorMessage}
      ariaInvalid={ariaInvalid}
      ariaLabel={ariaLabel}
      ariaRequired={ariaRequired}
      className={className}
      disabled={disabled}
      id={id}
      onBlur={onBlur}
      onChange={onChange}
      placeholder={placeholder}
      prefix={<FieldPrefixIcon icon={IconGlyph.Search} />}
      required={required}
      testId={testId}
      type={BaseTextFieldType.Search}
      value={value}
      suffix={
        value && !disabled ? (
          <FieldSuffixIconButton
            ariaLabel={t('ui.searchField.clear')}
            icon={IconGlyph.CloseCircle}
            onClick={handleClearClick}
          />
        ) : null
      }
    />
  );
}
