import { useState, useEffect } from 'react'
import { SearchIcon } from './SearchIcon'
import { ClearButton } from './ClearButton'
import { Input } from './ui'
import { t } from '@/lib/i18n'

interface SearchBarProps {
  value: string
  onChange: (value: string) => void
  placeholder?: string
}

export function SearchBar({ value, onChange, placeholder }: SearchBarProps): React.ReactElement {
  const defaultPlaceholder = placeholder ?? t('search.placeholder')
  const [localValue, setLocalValue] = useState(value)

  useEffect(() => {
    setLocalValue(value)
  }, [value])

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
    const newValue = e.target.value
    setLocalValue(newValue)
    onChange(newValue)
  }

  const handleClear = (): void => {
    setLocalValue('')
    onChange('')
  }

  return (
    <Input
      type="text"
      value={localValue}
      onChange={handleChange}
      placeholder={defaultPlaceholder}
      leftIcon={<SearchIcon />}
      rightIcon={localValue ? <ClearButton onClick={handleClear} /> : undefined}
      className="pr-10"
    />
  )
}
