import { useState } from 'react';

import { Group, Input } from '@chakra-ui/react';
import { MdSearch } from 'react-icons/md';

export type SearchInputProps = {
  onChange?: (data?: string) => void;
  onSubmit?: (data?: string) => void;
};

export const SearchInput = ({
  onChange: onChangeValue,
  onSubmit: onSubmitValue,
}: SearchInputProps) => {
  const [inputData, setInputData] = useState<string | undefined>(undefined);
  const [searchInputProperty, setSearchInputProperty] =
    useState<any>(undefined);
  function onFocusKeep(): void {
    setSearchInputProperty({
      width: '70%',
      maxWidth: '70%',
    });
  }
  function onFocusLost(): void {
    setSearchInputProperty({
      width: '250px',
    });
  }
  function onChange(event): void {
    const data =
      event.target.value.length === 0 ? undefined : event.target.value;
    setInputData(data);
    if (onChangeValue) {
      onChangeValue(data);
    }
  }
  function onSubmit(): void {
    if (onSubmitValue) {
      onSubmitValue(inputData);
    }
  }
  return (
    <Group maxWidth="200px" marginLeft="auto" {...searchInputProperty}>
      <MdSearch color="gray.300" />
      <Input
        onFocus={onFocusKeep}
        onBlur={() => setTimeout(() => onFocusLost(), 200)}
        onChange={onChange}
        onSubmit={onSubmit}
      />
    </Group>
  );
};
