import React, { useEffect, useRef, useMemo } from 'react'
import { Input } from 'react-aria-components'
import { Icon, ButtonAria } from '$core-components'
import './Search.scss'
import { t } from '$themelocalization'

const Search = ({
  value = '',
  className = '',
  placeholder = '',
  onChange,
  onSearch,
  onClose,
  autoFocus = false
}) => {

  const containerRef = useRef()

  const sanitizePlaceholder = (rawPlaceholder) => {
    if (rawPlaceholder === null || rawPlaceholder === undefined || rawPlaceholder === 'null') {
      return t('Addresses.Search.Placeholder') || 'Search address'
    }
    return rawPlaceholder
  }

  const placeholderValue = useMemo(() => sanitizePlaceholder(placeholder), [placeholder])

  useEffect(() => {
    if (autoFocus && className.includes('search-visible')) {
      containerRef?.current?.querySelector('input')?.focus()
    }
  }, [className, autoFocus])

  useEffect(() => {
    const input = containerRef?.current?.querySelector('input')
    if (!input) return

    const restorePlaceholder = () => {
      const currentPlaceholderAttr = input.getAttribute('placeholder')
      if (currentPlaceholderAttr === null || currentPlaceholderAttr === undefined || currentPlaceholderAttr === 'null') {
        input.setAttribute('placeholder', placeholderValue)
        input.placeholder = placeholderValue
      }
    }

    const observer = new MutationObserver(restorePlaceholder)

    observer.observe(input, {
      attributes: true,
      attributeFilter: ['placeholder'],
      attributeOldValue: true
    })

    return () => {
      observer.disconnect()
    }
  }, [placeholderValue])

  const handleSearch = () => {
    const trimmedValue = value?.trim() || ''
    if (onSearch) {
      onSearch(trimmedValue)
    }
  }

  const handleKeyDown = (event) => {
    if (event.key === 'Enter') {
      event.preventDefault()
      handleSearch()
      const input = containerRef?.current?.querySelector('input')
      if (input) {
        input.blur()
      }
    }
    if (event.key === 'Escape') {
      event.preventDefault()
      event.stopPropagation()

      handleClear()
      if (onClose) {
        onClose()
      }

      const input = containerRef?.current?.querySelector('input')
      if (input) {
        input.focus()
      }
    }
  }

  const handleChange = (e) => {
    if (onChange) {
      onChange(e.target.value ?? '')
    }
  }

  const handleClear = () => {
    if (onChange) {
      onChange('')
    }
    if (onSearch) {
      onSearch('')
    }
    const input = containerRef?.current?.querySelector('input')
    if (input) {
      input.focus()
    }
  }

  const inputValue = value || ''
  const hasValue = inputValue.trim().length > 0

  return (
    <div className={`search-addresses ${className}`} ref={containerRef}>
      <div className="search-input-wrapper">
        <Input
          type="text"
          className="search-input form-control"
          value={inputValue}
          placeholder={placeholderValue}
          aria-label={placeholderValue}
          onChange={handleChange}
          onKeyDown={handleKeyDown}
        />
        {hasValue && (
          <ButtonAria className="search-clear-button" onPress={handleClear} ariaLabel={t('General.ClearSearch')}>
            <Icon name="close_black.svg" width="15px" height="15px" className="search-clear-icon" ariaHidden="true" />
          </ButtonAria>
        )}
      </div>
      <ButtonAria className="search-button" onPress={handleSearch} ariaLabel={t('General.Search')}>
        <div className="search-icon-container">
          <Icon name="homepage_header_search.svg" width="21px" height="21px" className="search-icon" ariaHidden="true" />
        </div>
      </ButtonAria>
    </div>
  )
}

export default Search

