import { Minus, Plus } from "lucide-react";
import Input from "~/components/custom_ui/input";
export const Counter = ({
  value,
  setValue,
  name,
  onlyPositive,
  disabled,
}: {
  value: number;
  setValue: (value: number) => void;
  name: string;
  onlyPositive?: boolean;
  disabled?: boolean;
}) => {
  const handleChange = (change: number) => {
    const newValue = value + change;
    if (onlyPositive && newValue < 0) return;
    setValue(newValue);
  };
  return (
    <div className="w-[9.5rem]">
      <label htmlFor={name} className="sr-only">
        {name}
      </label>

      <div className="flex items-center rounded-md border px-1">
        <button
          type="button"
          onClick={() => handleChange(-1)}
          className="flex size-10 items-center justify-center leading-10 transition hover:opacity-75 disabled:opacity-50"
          disabled={disabled}
        >
          <Minus />
        </button>

        <Input
          type="number"
          id={name}
          value={value}
          onChange={(e) => {
            if (!Number.isNaN(Number.parseInt(e.target.value))) {
              setValue(Number.parseInt(e.target.value));
            } else {
              e.target.value = String(value);
            }
          }}
          disabled={disabled}
          className="no-spinner h-10 w-16 rounded-md border-none text-center shadow-none disabled:cursor-default sm:text-sm"
        />

        <button
          type="button"
          onClick={() => handleChange(1)}
          className="flex size-10 items-center justify-center leading-10 transition hover:opacity-75 disabled:opacity-50"
          disabled={disabled}
        >
          <Plus />
        </button>
      </div>
    </div>
  );
};
