import React, { useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from '@/hooks/useI18n';
import SearchInput from '@/components/ui/SearchInput';

interface SearchBarProps {
  value: string;
  onChange: (value: string) => void;
  onSubmit?: (value: string) => void;
  placeholder?: string;
  showClearButton?: boolean;
  onClear?: () => void;
  containerClassName?: string;
  navigateOnEnter?: boolean;
  navigatePath?: string;
}

export const SearchBar: React.FC<SearchBarProps> = ({
  value,
  onChange,
  onSubmit,
  placeholder,
  showClearButton = true,
  onClear,
  containerClassName,
  navigateOnEnter = false,
  navigatePath = '/map'
}) => {
  const { t } = useTranslation();
  const navigate = useNavigate();

  const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && value.trim()) {
      e.preventDefault();
      const searchValue = value.trim();

      if (onSubmit) {
        onSubmit(searchValue);
      } else if (navigateOnEnter) {
        navigate(`${navigatePath}?search=${encodeURIComponent(searchValue)}`);
      }
    }
  }, [value, onSubmit, navigateOnEnter, navigatePath, navigate]);

  const handleClear = useCallback(() => {
    onChange('');
    onClear?.();
  }, [onChange, onClear]);

  return (
    <div className={`w-full md:w-auto md:flex-1 max-w-md relative ${containerClassName}`}>
      <SearchInput
        placeholder={placeholder || t('mapHeader.searchPlaceholder')}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onKeyDown={handleKeyDown}
        showClearButton={showClearButton}
        onClear={handleClear}
        autoComplete="off"
        spellCheck="false"
      />
    </div>
  );
};

export default SearchBar;
