import { useState, useEffect, useRef } from "react";

function AutocompleteInput({ value, onChange, onKeyDown, suggestions = [], placeholder, inputRef, ...props }) {
  const [suggestion, setSuggestion] = useState("");
  const localRef = useRef(null);
  const ref = inputRef || localRef;

  useEffect(() => {
    if (value && suggestions.length > 0) {
      const match = suggestions.find(s => 
        s.toLowerCase().startsWith(value.toLowerCase()) && s.toLowerCase() !== value.toLowerCase()
      );
      setSuggestion(match || "");
    } else {
      setSuggestion("");
    }
  }, [value, suggestions]);

  const handleKeyDown = (e) => {
    if (e.key === 'Tab' && suggestion) {
      e.preventDefault();
      onChange({ target: { value: suggestion } });
      setSuggestion("");
    } else if (onKeyDown) {
      onKeyDown(e);
    }
  };

  return (
    <div className="autocomplete-wrapper">
      <input
        ref={ref}
        value={value}
        onChange={onChange}
        onKeyDown={handleKeyDown}
        placeholder={placeholder}
        {...props}
      />
      {suggestion && (
        <div className="autocomplete-suggestion">
          <span className="autocomplete-typed">{value}</span>
          <span className="autocomplete-rest">{suggestion.slice(value.length)}</span>
        </div>
      )}
    </div>
  );
}

export default AutocompleteInput;
