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

/**
 * Tabs (ARIA tablist with roving focus and arrow-key navigation).
 * tabs: [{ id, label, icon?, count? }]. When `hrefFor` is given the tabs
 * render as links (for page-level navigation) with aria-current.
 */
export function Tabs({ tabs, value, onChange, label, hrefFor, idPrefix = 'bp-tab' }) {
	const listRef = useRef(null);

	const onKeyDown = (e) => {
		if (hrefFor) return;
		const idx = tabs.findIndex((t) => t.id === value);
		let next = null;
		const rtl = listRef.current && getComputedStyle(listRef.current).direction === 'rtl';
		if (e.key === (rtl ? 'ArrowLeft' : 'ArrowRight')) next = (idx + 1) % tabs.length;
		if (e.key === (rtl ? 'ArrowRight' : 'ArrowLeft')) next = (idx - 1 + tabs.length) % tabs.length;
		if (e.key === 'Home') next = 0;
		if (e.key === 'End') next = tabs.length - 1;
		if (next === null) return;
		e.preventDefault();
		onChange(tabs[next].id);
		const btn = listRef.current && listRef.current.querySelector(`#${idPrefix}-${tabs[next].id}`);
		if (btn) btn.focus();
	};

	if (hrefFor) {
		return (
			<nav className="bp-tabs" aria-label={label}>
				{tabs.map((t) => (
					<a key={t.id} className="bp-tab" href={hrefFor(t.id)} aria-current={t.id === value ? 'page' : undefined}>
						{t.icon ? <Icon name={t.icon} /> : null}
						{t.label}
						{t.count != null ? <span className="bp-tab__count">{t.count}</span> : null}
					</a>
				))}
			</nav>
		);
	}

	return (
		<div className="bp-tabs" role="tablist" aria-label={label} ref={listRef} onKeyDown={onKeyDown}>
			{tabs.map((t) => {
				const selected = t.id === value;
				return (
					<button
						key={t.id}
						id={`${idPrefix}-${t.id}`}
						type="button"
						role="tab"
						className="bp-tab"
						aria-selected={selected ? 'true' : 'false'}
						aria-controls={`${idPrefix}-panel-${t.id}`}
						tabIndex={selected ? 0 : -1}
						onClick={() => onChange(t.id)}
					>
						{t.icon ? <Icon name={t.icon} /> : null}
						{t.label}
						{t.count != null ? <span className="bp-tab__count">{t.count}</span> : null}
					</button>
				);
			})}
		</div>
	);
}

export function TabPanel({ id, value, idPrefix = 'bp-tab', children }) {
	if (id !== value) return null;
	return (
		<div role="tabpanel" id={`${idPrefix}-panel-${id}`} aria-labelledby={`${idPrefix}-${id}`} tabIndex={0} style={{ outline: 'none' }}>
			{children}
		</div>
	);
}

/**
 * Segmented control (single choice among a few options).
 * options: [{ value, label }]
 */
export function Segmented({ options, value, onChange, label, size }) {
	return (
		<div className="bp-segmented" role="group" aria-label={label}>
			{options.map((o) => (
				<button
					key={o.value}
					type="button"
					className="bp-segmented__item"
					aria-pressed={o.value === value ? 'true' : 'false'}
					onClick={() => onChange(o.value)}
					style={size === 'sm' ? { minHeight: 26 } : undefined}
				>
					{o.label}
				</button>
			))}
		</div>
	);
}
