import React, { useRef } from 'react';
import { Icon } from '../../../shared/ui';

/**
 * Selectable cards (services, staff, locations…).
 *
 * Single choice: a radiogroup with roving focus (arrow keys move, Space/Enter
 * selects). Multiple choice: independent toggle buttons.
 *
 * onSelect(id, { pointer }) — `pointer` is true for mouse/touch activation, so
 * the wizard can move on automatically without surprising keyboard users.
 *
 * @param {Array<{id, title, desc?, media?, meta?, aside?, disabled?}>} items
 */
export default function OptionList({ items, value, onSelect, multiple = false, label, labelledBy, columns = 1 }) {
	const listRef = useRef(null);
	const isSelected = (id) => (multiple ? (value || []).some((v) => String(v) === String(id)) : value !== null && value !== undefined && String(value) === String(id));
	const selectedIndex = items.findIndex((it) => isSelected(it.id));
	const tabIndexFor = (i) => {
		if (multiple) return 0;
		if (selectedIndex >= 0) return i === selectedIndex ? 0 : -1;
		return i === 0 ? 0 : -1;
	};

	const onKeyDown = (e) => {
		if (multiple) return;
		const keys = ['ArrowDown', 'ArrowRight', 'ArrowUp', 'ArrowLeft', 'Home', 'End'];
		if (!keys.includes(e.key)) return;
		const buttons = Array.from(listRef.current?.querySelectorAll('[role="radio"]:not([disabled])') || []);
		const idx = buttons.indexOf(document.activeElement);
		if (idx === -1) return;
		e.preventDefault();
		const rtl = getComputedStyle(listRef.current).direction === 'rtl';
		let nextIdx = idx;
		if (e.key === 'Home') nextIdx = 0;
		else if (e.key === 'End') nextIdx = buttons.length - 1;
		else {
			let forward = e.key === 'ArrowDown' || e.key === 'ArrowRight';
			if (rtl && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) forward = !forward;
			nextIdx = (idx + (forward ? 1 : -1) + buttons.length) % buttons.length;
		}
		const target = buttons[nextIdx];
		target.focus();
		// Radio pattern: moving with the arrows also checks the option.
		const item = items.find((it) => String(it.id) === target.getAttribute('data-option-id'));
		if (item) onSelect(item.id, { pointer: false });
	};

	return (
		<div
			ref={listRef}
			className={['bp-bw-options', columns > 1 ? 'bp-bw-options--grid' : ''].filter(Boolean).join(' ')}
			role={multiple ? 'group' : 'radiogroup'}
			aria-label={label}
			aria-labelledby={labelledBy}
			onKeyDown={onKeyDown}
		>
			{items.map((it, i) => {
				const selected = isSelected(it.id);
				return (
					<button
						key={it.id}
						type="button"
						className={['bp-option-card', it.className || ''].filter(Boolean).join(' ')}
						role={multiple ? undefined : 'radio'}
						aria-checked={multiple ? undefined : selected ? 'true' : 'false'}
						aria-pressed={multiple ? (selected ? 'true' : 'false') : undefined}
						tabIndex={tabIndexFor(i)}
						disabled={it.disabled}
						data-option-id={it.id}
						onClick={(e) => onSelect(it.id, { pointer: e.detail > 0 })}
					>
						{it.media ? <span className="bp-option-card__media">{it.media}</span> : null}
						<span className="bp-option-card__body">
							<span className="bp-option-card__title">{it.title}</span>
							{it.desc ? <span className="bp-option-card__desc">{it.desc}</span> : null}
							{it.meta ? <span className="bp-option-card__meta">{it.meta}</span> : null}
						</span>
						<span className="bp-option-card__aside">
							{it.aside ? <span className="bp-option-card__price">{it.aside}</span> : null}
							<span className={['bp-option-card__indicator', multiple ? 'bp-option-card__indicator--square' : ''].filter(Boolean).join(' ')} aria-hidden="true">
								<Icon name="check" />
							</span>
						</span>
					</button>
				);
			})}
		</div>
	);
}
