import React, { useState, useRef } from 'react'
import { t } from '$themelocalization'
import { Icon } from '$core-components'
import './index.scss'

const DraftSearchBar = ({ value, onChange }) => {
  const [inputValue, setInputValue] = useState(value || '')
  const inputRef = useRef(null)

  const handleChange = (e) => {
    const newValue = e.target.value ?? ''
    setInputValue(newValue)
  }

  const handleClear = () => {
    setInputValue('')
    onChange('')
    inputRef.current?.focus()
  }

  const handleKeyDown = (e) => {
    if (e.key === 'Escape') {
      e.preventDefault()
      e.stopPropagation()
      handleClear()
    } else if (e.key === 'Enter') {
      e.preventDefault()
      onChange(inputValue || '')
    }
  }

  const handleSearch = () => {
    onChange(inputValue || '')
  }

  return (
    <div className="draft-search-bar">
      <input
        ref={inputRef}
        type="text"
        className="draft-search-input"
        placeholder={t('Drafts.Search.Placeholder')}
        value={inputValue}
        onChange={handleChange}
        onKeyDown={handleKeyDown}
      />
      {inputValue && (
        <button
          className="draft-search-clear"
          onClick={handleClear}
          aria-label={t('Drafts.Search.Clear')}
        >
          <Icon name="close_black.svg" width="12px" height="12px" />
        </button>
      )}
      <button
        className="draft-search-button"
        onClick={handleSearch}
        aria-label={t('Drafts.Search.Search')}
      >
        <Icon name="homepage_header_search.svg" width="20px" height="20px" />
      </button>
    </div>
  )
}

export default DraftSearchBar
