import { Minus, Plus } from "lucide-react";
import Input from "~/components/ui/input";
import { cn } from "~/lib/utils";
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-38 bg-card">
			<label className="sr-only" htmlFor={name}>
				{name}
			</label>

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

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

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