import React from 'react';
import { __ } from '@wordpress/i18n';
import { Avatar, EmptyState, Icon } from '../../../shared/ui';
import OptionList from './OptionList';
import { formatDuration, formatMoney } from '../format';

const Thumb = ({ src, icon }) => (src ? <img src={src} alt="" loading="lazy" decoding="async" /> : <Icon name={icon} size={22} />);

export function LocationStep({ flow, labelledBy }) {
	const rows = flow.data.locations || [];
	return (
		<OptionList
			labelledBy={labelledBy}
			value={flow.sel.locationId}
			onSelect={(id, { pointer }) => (pointer ? flow.actions.pickAndNext({ locationId: id }) : flow.actions.update({ locationId: id }))}
			items={rows.map((r) => ({
				id: r.id,
				title: r.name,
				desc: r.address || '',
				media: <Thumb src={r.image_url} icon="map-pin" />,
			}))}
		/>
	);
}

export function CategoryStep({ flow, labelledBy }) {
	const rows = flow.data.categories || [];
	return (
		<OptionList
			labelledBy={labelledBy}
			columns={2}
			value={flow.sel.categoryId}
			onSelect={(id, { pointer }) => (pointer ? flow.actions.pickAndNext({ categoryId: id }) : flow.actions.update({ categoryId: id }))}
			items={rows.map((r) => ({
				id: r.id,
				title: r.name,
				media: <Thumb src={r.image_url} icon="layers" />,
			}))}
		/>
	);
}

export function ServiceStep({ flow, labelledBy }) {
	const rows = flow.data.services || [];
	if (!rows.length) {
		return (
			<EmptyState icon="briefcase" title={__('No services available', 'pointly-booking')}>
				{__('There is nothing to book here right now. Please try again later.', 'pointly-booking')}
			</EmptyState>
		);
	}
	return (
		<OptionList
			labelledBy={labelledBy}
			value={flow.sel.serviceId}
			onSelect={(id, { pointer }) => (pointer ? flow.actions.pickAndNext({ serviceId: id }) : flow.actions.update({ serviceId: id }))}
			items={rows.map((r) => ({
				id: r.id,
				title: r.name,
				desc: r.description || '',
				media: <Thumb src={r.image_url} icon="briefcase" />,
				meta: r.duration ? (
					<span>
						<Icon name="clock" />
						{formatDuration(r.duration)}
					</span>
				) : null,
				aside: Number(r.price) > 0 ? formatMoney(r.price, r.currency) : __('Free', 'pointly-booking'),
			}))}
		/>
	);
}

export function ExtrasStep({ flow, labelledBy }) {
	const rows = flow.data.extras || [];
	const toggle = (id) => {
		const cur = flow.sel.extraIds;
		const on = cur.some((v) => String(v) === String(id));
		flow.actions.update({ extraIds: on ? cur.filter((v) => String(v) !== String(id)) : [...cur, id] });
	};
	return (
		<>
			<p className="bp-bw-hint">{__('Select as many as you like, or continue without extras.', 'pointly-booking')}</p>
			<OptionList
				labelledBy={labelledBy}
				multiple
				value={flow.sel.extraIds}
				onSelect={(id) => toggle(id)}
				items={rows.map((r) => ({
					id: r.id,
					title: r.name,
					desc: r.description || r.desc || '',
					media: <Thumb src={r.image_url} icon="sparkles" />,
					meta: Number(r.duration_minutes || r.duration) > 0 ? (
						<span>
							<Icon name="clock" />
							{formatDuration(r.duration_minutes || r.duration)}
						</span>
					) : null,
					aside: Number(r.price) > 0 ? `+${formatMoney(r.price, flow.service?.currency)}` : __('Included', 'pointly-booking'),
				}))}
			/>
		</>
	);
}

export function agentName(a) {
	return a?.name || [a?.first_name, a?.last_name].filter(Boolean).join(' ') || '';
}

export function AgentStep({ flow, labelledBy }) {
	const rows = flow.data.agents || [];
	if (!rows.length) {
		return (
			<EmptyState icon="users" title={__('No staff available', 'pointly-booking')}>
				{__('Nobody is available for this service at the moment. Please choose another service.', 'pointly-booking')}
			</EmptyState>
		);
	}
	const items = [
		{
			id: 0,
			title: __('Any available', 'pointly-booking'),
			desc: __('We will book whoever is free at your chosen time.', 'pointly-booking'),
			media: <Icon name="sparkles" size={22} />,
			className: 'bp-bw-any',
		},
		...rows.map((a) => ({
			id: a.id,
			title: agentName(a),
			desc: a.title || '',
			media: <Avatar name={agentName(a)} src={a.image_url || undefined} size="lg" />,
		})),
	];
	return (
		<OptionList
			labelledBy={labelledBy}
			value={flow.sel.agentId}
			onSelect={(id, { pointer }) => (pointer ? flow.actions.pickAndNext({ agentId: id }) : flow.actions.update({ agentId: id }))}
			items={items}
		/>
	);
}
