'use client';

import { randInRange } from '@/lib/utils';
import styles from '../styles/QuantityCard.module.css';

type Props = {
	id: string;
	name: string;
	iconUrl: string;
	qty: number;
	randMin: number;
	randMax: number;
	onSetQty: (id: string, qty: number) => void;
};

const clamp = (v: number) => Math.min(32767, Math.max(0, v));

export default function QuantityCard({
	id,
	name,
	iconUrl,
	qty,
	randMin,
	randMax,
	onSetQty
}: Props) {
	const active = qty > 0;

	return (
		<div className={`${styles.card} ${active ? styles.cardActive : ''}`}>
			<img className={styles.icon} src={iconUrl} alt={name} loading='lazy' />
			<span className={styles.name}>{name}</span>

			{active ? (
				<>
					<div className={styles.qtyRow}>
						<button
							className={styles.qtyBtn}
							onClick={() => onSetQty(id, clamp(qty - 1))}
						>
							−
						</button>
						<input
							className={styles.qtyInput}
							type='number'
							value={qty}
							min={0}
							max={5000}
							onChange={(e) => {
								const v = parseInt(e.target.value);
								if (!isNaN(v)) onSetQty(id, clamp(v));
							}}
						/>
						<button
							className={styles.qtyBtn}
							onClick={() => onSetQty(id, clamp(qty + 1))}
						>
							+
						</button>
					</div>

					<div className={styles.quickRow}>
						<button
							className={styles.quickBtn}
							onClick={() => onSetQty(id, 100)}
						>
							100
						</button>
						<button
							className={`${styles.quickBtn} ${styles.quickBtnRand}`}
							onClick={() => onSetQty(id, randInRange(randMin, randMax))}
						>
							rand
						</button>
						<button
							className={`${styles.quickBtn} ${styles.quickBtnRemove}`}
							onClick={() => onSetQty(id, 0)}
						>
							✕
						</button>
					</div>
				</>
			) : (
				<button className={styles.addBtn} onClick={() => onSetQty(id, 100)}>
					+ Add
				</button>
			)}
		</div>
	);
}
