import React, { useMemo } from 'react';
import { __ } from '@wordpress/i18n';
import Icon from '../icons/Icon';

const toMinutes = (t) => {
	const m = /^(\d{1,2}):(\d{2})/.exec(String(t || ''));
	return m ? Number(m[1]) * 60 + Number(m[2]) : -1;
};

export function dayPart(time) {
	const m = toMinutes(time);
	if (m < 720) return 'morning';
	if (m < 1020) return 'afternoon';
	return 'evening';
}

/**
 * Formats "HH:MM" for display in the site's preferred clock (12h/24h).
 */
export function formatTime(time, { hour12, locale } = {}) {
	const m = toMinutes(time);
	if (m < 0) return String(time || '');
	const d = new Date(Date.UTC(2023, 0, 1, Math.floor(m / 60), m % 60));
	return new Intl.DateTimeFormat(locale || undefined, {
		hour: 'numeric',
		minute: '2-digit',
		hour12: hour12 === undefined ? undefined : !!hour12,
		timeZone: 'UTC',
	}).format(d);
}

const GROUPS = [
	{ key: 'morning', icon: 'sunrise', label: () => __('Morning', 'pointly-booking') },
	{ key: 'afternoon', icon: 'sun', label: () => __('Afternoon', 'pointly-booking') },
	{ key: 'evening', icon: 'sunset', label: () => __('Evening', 'pointly-booking') },
];

/**
 * Time slot picker grouped into morning / afternoon / evening.
 *
 * @param {Array<{time:string, label?:string, disabled?:boolean}>} slots  time = 'HH:MM'
 * @param {string}   value     Selected 'HH:MM'.
 * @param {Function} onChange  (time, slot, event) => void
 * @param {Object}   [format]  { hour12, locale }
 */
export default function TimeSlots({ slots = [], value, onChange, format = {}, groupLabelledBy }) {
	const grouped = useMemo(() => {
		const out = { morning: [], afternoon: [], evening: [] };
		slots.forEach((s) => out[dayPart(s.time)].push(s));
		return out;
	}, [slots]);

	return (
		<div className="bp-slot-groups" role="radiogroup" aria-labelledby={groupLabelledBy}>
			{GROUPS.map((g) => {
				const list = grouped[g.key];
				if (!list.length) return null;
				const labelId = `bp-slot-group-${g.key}`;
				return (
					<div key={g.key} className="bp-slot-group" role="group" aria-labelledby={labelId}>
						<div className="bp-slot-group__label" id={labelId}>
							<Icon name={g.icon} />
							{g.label()}
							<span className="bp-text-subtle">({list.length})</span>
						</div>
						<div className="bp-slot-list">
							{list.map((s) => {
								const selected = value === s.time;
								return (
									<button
										key={s.time}
										type="button"
										role="radio"
										aria-checked={selected ? 'true' : 'false'}
										className="bp-slot"
										disabled={s.disabled}
										onClick={(e) => onChange && onChange(s.time, s, e)}
									>
										<bdi>{s.label || formatTime(s.time, format)}</bdi>
									</button>
								);
							})}
						</div>
					</div>
				);
			})}
		</div>
	);
}
