import { useState } from "react";

export const QuantityControl: React.FC<{
  quantity: number;
  onIncrease: () => void;
  onDecrease: () => void;
  onChangeQuantity: (qty: number) => void;
  price: number;
  loading: boolean;
  max?: number;
  onMaxLimitReached: () => void;
}> = ({
  quantity,
  onIncrease,
  onDecrease,
  onChangeQuantity,
  price,
  loading,
  max,
  onMaxLimitReached,
}) => {
  const MAX_QTY = max ?? 10000;

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const raw = e.target.value;

    if (raw === "") {
      onChangeQuantity(0);
      return;
    }

    // ❌ no decimal / negative / e
    if (!/^\d+$/.test(raw)) return;

    const next = parseInt(raw, 10);

    if (next > MAX_QTY) {
      onMaxLimitReached(); // 🚨 modal open
      return;
    }

    onChangeQuantity(next);
  };

  return (
    <div className="flex items-center gap-4">
      <p className="text-white text-xs md:text-lg 2xl:text-[25px] bg-(--color-naviBlue) px-4 border border-transparent py-3 md:py-2 2xl:py-3 font-sofia font-bold">
        {price}
      </p>
      <div className="flex items-center bg-(--color-gray) justify-center gap-6 py-1 2xl:py-3">
        <button
          onClick={onDecrease}
          disabled={quantity <= 0}
          className="text-white cursor-pointer flex px-4 py-2 items-center justify-center disabled:opacity-40"
        >
          <img src="/images/shop/minus.svg" alt="-" />
        </button>

        {/* ✅ Manual Input */}
        {/* {quantity} */}

        <div className="text-center min-w-25">
          <div className="flex items-center justify-center gap-2 mt-2">
            <input
              type="text"
              inputMode="numeric"
              pattern="[0-9]*"
              value={quantity}
              onChange={handleInputChange}
              disabled={loading}
              className="
    w-20 md:w-25 2xl:w-30
    

    text-center
    bg-transparent
    text-white
    text-sm md:text-lg 2xl:text-xl
    font-medium font-sofia
    outline-none

    leading-none
    md:py-1

    [appearance:textfield]
    [&::-webkit-outer-spin-button]:appearance-none
    [&::-webkit-inner-spin-button]:appearance-none
  "
            />
          </div>
        </div>
        <button
          onClick={onIncrease}
          className={`text-white ${
            loading
              ? "cursor-not-allowed pointer-events-none"
              : " cursor-pointer"
          } flex items-center px-4 py-2 justify-center`}
        >
          <img src="/images/shop/plus.svg" alt="+" />
        </button>
      </div>
    </div>
  );
};
