import { useState } from "react";
import "../../styles/ConfirmBuyModal.css";

export default function ConfirmBuyModal({ item, onConfirm, onCancel }) {
  const [quantity, setQuantity] = useState(item.quantity);
  const maxQuantity = item.quantity;

  const handleIncrement = () => {
    if (quantity < maxQuantity) {
      setQuantity(prev => prev + 1);
    }
  };

  const handleDecrement = () => {
    if (quantity > 1) {
      setQuantity(prev => prev - 1);
    }
  };

  const handleConfirm = () => {
    onConfirm(quantity);
  };

  return (
    <div className="confirm-buy-modal-overlay" onClick={onCancel}>
      <div className="confirm-buy-modal" onClick={(e) => e.stopPropagation()}>
        <h2>Mark as Bought</h2>
        <p className="confirm-buy-item-name">"{item.item_name}"</p>

        <div className="confirm-buy-quantity-section">
          <p className="confirm-buy-label">Quantity to buy:</p>
          <div className="confirm-buy-counter">
            <button
              onClick={handleDecrement}
              className="confirm-buy-counter-btn"
              disabled={quantity <= 1}
            >
              −
            </button>
            <input
              type="number"
              value={quantity}
              readOnly
              className="confirm-buy-counter-display"
            />
            <button
              onClick={handleIncrement}
              className="confirm-buy-counter-btn"
              disabled={quantity >= maxQuantity}
            >
              +
            </button>
          </div>
        </div>

        <div className="confirm-buy-actions">
          <button onClick={onCancel} className="confirm-buy-cancel">
            Cancel
          </button>
          <button onClick={handleConfirm} className="confirm-buy-confirm">
            Mark as Bought
          </button>
        </div>
      </div>
    </div>
  );
}
