import { useState } from 'react'
import { TextInput } from '../TextInput/index.js'
import { IconButton } from '../IconButton/index.js'

type SearchInputProps = {
  value?: string
  onChange: (value: string) => void
}

function SearchInput({ value, onChange }: SearchInputProps) {
  const [open, setOpen] = useState(false)

  if (open) {
    return (
      <TextInput
        autoFocus
        value={value}
        onChange={onChange}
        onBlur={(e) => {
          if (!e.target.value) {
            setOpen(false)
          }
        }}
      />
    )
  }

  return (
    <IconButton
      icon="search"
      onClick={() => {
        setOpen(true)
      }}
    />
  )
}

export { SearchInput }
export type { SearchInputProps }
