import React, { useId, useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { Button, Icon } from '../../../shared/ui';
import { agentName } from './ChoiceSteps';
import { addMinutes, formatClock, formatDate, formatDuration, formatMoney } from '../format';

/**
 * Rows describing the current selection: [{ key, step, icon, label, value }].
 * `step` is the wizard step that edits the row.
 */
export function selectionRows(flow) {
	const { sel, data, service, selectedExtras } = flow;
	const rows = [];
	if (service) {
		rows.push({
			key: 'service',
			step: 'service',
			icon: 'briefcase',
			label: __('Service', 'pointly-booking'),
			value: service.name,
			sub: formatDuration(service.duration),
		});
	}
	if (selectedExtras.length) {
		rows.push({ key: 'extras', step: 'extras', icon: 'sparkles', label: __('Extras', 'pointly-booking'), value: selectedExtras.map((x) => x.name).join(', ') });
	}
	if (sel.agentId !== null) {
		const agent = (data.agents || []).find((a) => String(a.id) === String(sel.agentId));
		rows.push({
			key: 'agent',
			step: 'agent',
			icon: 'user',
			label: __('Staff', 'pointly-booking'),
			value: sel.agentId === 0 || !agent ? __('Any available', 'pointly-booking') : agentName(agent),
		});
	}
	if (sel.locationId) {
		const loc = (data.locations || []).find((l) => String(l.id) === String(sel.locationId));
		if (loc) rows.push({ key: 'location', step: 'location', icon: 'map-pin', label: __('Location', 'pointly-booking'), value: loc.name, sub: loc.address || '' });
	}
	if (sel.date) {
		const end = sel.time && service ? addMinutes(sel.time, service.duration || 0) : '';
		rows.push({
			key: 'datetime',
			step: 'datetime',
			icon: 'calendar',
			label: __('Date & time', 'pointly-booking'),
			value: formatDate(sel.date),
			/* translators: 1: start time, 2: end time. */
			sub: sel.time ? (end ? sprintf(__('%1$s – %2$s', 'pointly-booking'), formatClock(sel.time), formatClock(end)) : formatClock(sel.time)) : __('Pick a time', 'pointly-booking'),
		});
	}
	return rows;
}

export function PriceLines({ flow }) {
	const p = flow.pricing;
	if (!p) return null;
	const cur = p.currency;
	return (
		<dl className="bp-bw-price">
			{p.discount > 0 ? (
				<>
					<div className="bp-bw-price__row">
						<dt>{__('Subtotal', 'pointly-booking')}</dt>
						<dd>{formatMoney(p.subtotal, cur)}</dd>
					</div>
					<div className="bp-bw-price__row bp-bw-price__row--discount">
						<dt>
							{
								/* translators: %s: promo code. */
								p.promo_code ? sprintf(__('Discount (%s)', 'pointly-booking'), p.promo_code) : __('Discount', 'pointly-booking')
							}
						</dt>
						<dd>−{formatMoney(p.discount, cur)}</dd>
					</div>
				</>
			) : null}
			<div className="bp-bw-price__row bp-bw-price__row--total">
				<dt>{__('Total', 'pointly-booking')}</dt>
				<dd>{p.total > 0 ? formatMoney(p.total, cur) : __('Free', 'pointly-booking')}</dd>
			</div>
		</dl>
	);
}

export function SummaryList({ flow, editable = false }) {
	const rows = selectionRows(flow);
	if (!rows.length) {
		return <p className="bp-bw-hint">{__('Your choices will appear here.', 'pointly-booking')}</p>;
	}
	return (
		<ul className="bp-bw-sumlist">
			{rows.map((r) => (
				<li key={r.key} className="bp-bw-sumlist__row">
					<span className="bp-bw-sumlist__icon" aria-hidden="true">
						<Icon name={r.icon} />
					</span>
					<span className="bp-bw-sumlist__text">
						<span className="bp-bw-sumlist__label">{r.label}</span>
						<span className="bp-bw-sumlist__value">{r.value}</span>
						{r.sub ? <span className="bp-bw-sumlist__sub">{r.sub}</span> : null}
					</span>
					{editable && flow.history.includes(r.step) ? (
						<Button
							variant="link"
							size="sm"
							className="bp-bw-sumlist__edit"
							onClick={() => flow.actions.goTo(r.step)}
							aria-label={
								/* translators: %s: what is edited, e.g. "Service". */
								sprintf(__('Change %s', 'pointly-booking'), r.label)
							}
						>
							{__('Change', 'pointly-booking')}
						</Button>
					) : null}
				</li>
			))}
		</ul>
	);
}

/** Desktop side panel. */
export function SummaryPanel({ flow }) {
	return (
		<aside className="bp-bw-summary" aria-label={__('Booking summary', 'pointly-booking')}>
			<h2 className="bp-bw-summary__title">{__('Summary', 'pointly-booking')}</h2>
			<SummaryList flow={flow} />
			<PriceLines flow={flow} />
		</aside>
	);
}

/** Mobile: sticky bar with the total that expands into the full summary. */
export function SummaryBar({ flow }) {
	const [open, setOpen] = useState(false);
	const panelId = `bp-bw-sumbar-${useId().replace(/:/g, '')}`;
	const rows = selectionRows(flow);
	if (!rows.length) return null;
	const p = flow.pricing;
	return (
		<div className={['bp-bw-sumbar', open ? 'is-open' : ''].filter(Boolean).join(' ')}>
			<div id={panelId} className="bp-bw-sumbar__panel" hidden={!open}>
				<SummaryList flow={flow} />
				<PriceLines flow={flow} />
			</div>
			<button type="button" className="bp-bw-sumbar__toggle" aria-expanded={open ? 'true' : 'false'} aria-controls={panelId} onClick={() => setOpen((o) => !o)}>
				<span className="bp-bw-sumbar__label">
					<Icon name="receipt" />
					{open ? __('Hide summary', 'pointly-booking') : __('Show summary', 'pointly-booking')}
				</span>
				<span className="bp-bw-sumbar__total">
					{p ? (p.total > 0 ? formatMoney(p.total, p.currency) : __('Free', 'pointly-booking')) : null}
					<Icon name={open ? 'chevron-down' : 'chevron-up'} />
				</span>
			</button>
		</div>
	);
}
