// resources\assets\ts\ContactsPage\components\SearchBar.tsx
import React, { useEffect, useRef } from 'react';
import { msg } from '@lingui/macro';
import { useLingui } from '@lingui/react';

interface SearchBarProps {
  value: string;
  onChange: (newValue: string) => void;
}

const SearchBar: React.FC<SearchBarProps> = ({ value, onChange }) => {
  const { i18n } = useLingui();
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      const active = document.activeElement;

      const isInputFocused =
        active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || (active as HTMLElement).isContentEditable);

      
      if (!isInputFocused && event.key.length === 1 && !event.metaKey && !event.ctrlKey && !event.altKey) {
        inputRef.current?.focus();
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, []);

  return (
    <div
      className="form-group mb-2 position-relative"
      style={{ width: '100%' }}
    >
      <input
        ref={inputRef}
        type="text"
        className="form-control pe-5"
        id="idSearch"
        placeholder={i18n._(msg`Search by ID, short name, employee or company...`)}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{ width: '100%', borderRadius: '10px' }} 
      />

      {value && (
        <button
          type="button"
          className="btn position-absolute bg-transparent border-0 p-0"
          style={{
            right: '12px',
            top: '50%',
            transform: 'translateY(-50%)',
            cursor: 'pointer',
            color: '#555',
          }}
          onClick={() => onChange('')}
          aria-label={i18n._(msg`Clear input`)}
        >
          <i className="fa fa-times"></i>
        </button>
      )}
    </div>
  );
};

export default SearchBar;
