import React, { useEffect, useState } from 'react';
import { SilkeBox } from '../silke-box';
import { SilkeButton } from '../silke-button';
import { SilkeIcon } from '../silke-icon';
import { SilkeTextField, SilkeTextFieldItem, SingleLineProps } from '../silke-text-field';
import { useTextFieldContext } from '../silke-text-field/text-field-context';

type SilkeSearchFieldProps = {
  search?: string;
  onClearButton?: () => void;
} & Omit<SingleLineProps, 'value' | 'label'>;

export function SilkeSearchField({ search, onClearButton, ...rest }: SilkeSearchFieldProps) {
  const context = useTextFieldContext();
  const size = rest.size || context.size || 'base';
  const [value, setValue] = useState('');
  useEffect(() => {
    setValue(search || '');
  }, [search]);

  const handleChange = (value: string) => {
    setValue(value);
    if (rest.onChange) rest.onChange(value);
  };

  const handleClear = () => {
    setValue('');
    onClearButton?.();
    if (rest.onChange) rest.onChange('');
  };

  return (
    <SilkeTextField kind="ghost" {...rest} value={value} onChange={handleChange} size={size} inline>
      <SilkeTextFieldItem before align="center">
        <SilkeBox width={size} align="center">
          <SilkeIcon icon="search" />
        </SilkeBox>
      </SilkeTextFieldItem>
      {value && (
        <SilkeTextFieldItem>
          <SilkeButton icon="close" kind="ghost" size={size} onClick={handleClear} />
        </SilkeTextFieldItem>
      )}
    </SilkeTextField>
  );
}
