import React, { useMemo } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { formatDate, formatTime, formatWeekday, siteToday, splitDateTime } from '../../core/format';
import { monthGrid, weekDays } from './dates';

const MAX_CHIPS = 3;

/** Month view: 5–6 week grid with booking chips. Clicking a day opens it in the Day view. */
export default function MonthGrid({ date, events, onOpen, onDayOpen, onCreate }) {
	const today = siteToday();
	const days = useMemo(() => monthGrid(date), [date]);
	const heads = useMemo(() => weekDays(date), [date]);
	const byDay = useMemo(() => {
		const map = new Map();
		events.forEach((e) => {
			const d = splitDateTime(e.start).date;
			if (!map.has(d)) map.set(d, []);
			map.get(d).push(e);
		});
		map.forEach((list) => list.sort((a, b) => String(a.start).localeCompare(String(b.start))));
		return map;
	}, [events]);
	const month = date.slice(0, 7);

	return (
		<div className="bp-cal-month" role="group" aria-label={__('Month calendar', 'pointly-booking')}>
			<div className="bp-cal-month__head" aria-hidden="true">
				{heads.map((d) => (
					<div key={d}>{formatWeekday(d, 'short')}</div>
				))}
			</div>
			<div className="bp-cal-month__grid" style={{ gridTemplateRows: `repeat(${days.length / 7}, minmax(112px, 1fr))` }}>
				{days.map((d) => {
					const list = byDay.get(d) || [];
					const inMonth = d.slice(0, 7) === month;
					const visible = list.slice(0, MAX_CHIPS);
					return (
						<div key={d} className={['bp-cal-month__cell', inMonth ? '' : 'is-outside', d === today ? 'is-today' : ''].filter(Boolean).join(' ')} onDoubleClick={() => onCreate && onCreate(d)}>
							<button type="button" className="bp-cal-month__num" onClick={() => onDayOpen(d)} aria-label={sprintf(/* translators: 1: date, 2: number of bookings. */ __('%1$s, %2$d bookings — open day', 'pointly-booking'), formatDate(d, { weekday: 'long', day: 'numeric', month: 'long' }), list.length)}>
								{Number(d.slice(8))}
							</button>
							<ul>
								{visible.map((e) => (
									<li key={e.id}>
										<button type="button" className={['bp-cal-chip', `is-${e.status || 'pending'}`].join(' ')} onClick={() => onOpen(e)}>
											<span className="bp-cal-chip__time">{formatTime(splitDateTime(e.start).time)}</span>
											<span className="bp-cal-chip__title">{e.customer_name || e.service_name}</span>
										</button>
									</li>
								))}
							</ul>
							{list.length > MAX_CHIPS ? (
								<button type="button" className="bp-cal-month__more" onClick={() => onDayOpen(d)}>
									{sprintf(/* translators: %d: number of additional bookings. */ __('+%d more', 'pointly-booking'), list.length - MAX_CHIPS)}
								</button>
							) : null}
						</div>
					);
				})}
			</div>
		</div>
	);
}
