import { useState } from "react";
import "../../styles/components/AddItemForm.css";
import SuggestionList from "../items/SuggestionList";

export default function AddItemForm({ onAdd, onSuggest, suggestions, buttonText = "Add" }) {
  const [itemName, setItemName] = useState("");
  const [quantity, setQuantity] = useState(1);
  const [showSuggestions, setShowSuggestions] = useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!itemName.trim()) return;

    onAdd(itemName, quantity);
    setItemName("");
    setQuantity(1);
  };

  const handleInputChange = (text) => {
    setItemName(text);
    onSuggest(text);
  };

  const handleSuggestionSelect = (suggestion) => {
    setItemName(suggestion);
    setShowSuggestions(false);
    onSuggest(suggestion); // Trigger button text update
  };

  const incrementQuantity = () => {
    setQuantity(prev => prev + 1);
  };

  const decrementQuantity = () => {
    setQuantity(prev => Math.max(1, prev - 1));
  };

  const isDisabled = !itemName.trim();

  return (
    <div className="add-item-form-container">
      <form onSubmit={handleSubmit} className="add-item-form">
        <div className="add-item-form-field">
          <input
            type="text"
            className="add-item-form-input"
            placeholder="Enter item name"
            value={itemName}
            onChange={(e) => handleInputChange(e.target.value)}
            onBlur={() => setTimeout(() => setShowSuggestions(false), 150)}
            onClick={() => setShowSuggestions(true)}
          />

          {showSuggestions && suggestions.length > 0 && (
            <SuggestionList
              suggestions={suggestions}
              onSelect={handleSuggestionSelect}
            />
          )}
        </div>

        <div className="add-item-form-actions">
          <div className="add-item-form-quantity-control">
            <button
              type="button"
              className="quantity-btn quantity-btn-minus"
              onClick={decrementQuantity}
              disabled={quantity <= 1}
            >
              −
            </button>
            <input
              type="number"
              min="1"
              className="add-item-form-quantity-input"
              value={quantity}
              readOnly
            />
            <button
              type="button"
              className="quantity-btn quantity-btn-plus"
              onClick={incrementQuantity}
            >
              +
            </button>
          </div>

          <button
            type="submit"
            className={`add-item-form-submit ${isDisabled ? 'disabled' : ''}`}
            disabled={isDisabled}
          >
            {buttonText}
          </button>
        </div>
      </form>
    </div>
  );
}
