import React, { Component, useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls, getColorClassName } from '@wordpress/block-editor';
import { PanelBody, ToggleControl, FormTokenField, SelectControl } from '@wordpress/components';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import { Box, Stack, Paper, Typography, Button, List, ListItem, ListItemButton, ListItemIcon, ListItemText, Avatar } from '@mui/material';
import { CalendarMonthOutlined, PersonOutlineOutlined, PaymentOutlined, DoneOutlined, PersonOutlined, CheckCircle } from '@mui/icons-material';
import ServiceIcon from './assets/service.png';
import DateIcon from './assets/date.png';
import InfoIcon from './assets/info.png';
import PaymentIcon from './assets/payment.png';
import ConfirmIcon from './assets/confirm.png';
import LocationIcon from './assets/location.png';
import StaffIcon from "./assets/staff.png";
import { CustomFieldsProvider } from "../frontend/CustomFieldsContext";
import CustomFieldsInspector from './components/CustomFieldsInspector';
import InformationStepPreview from './components/InformationStepPreview';

const hideFormTokenFieldHelp = `.components-form-token-field__label { display: none !important; }`;

if (typeof document !== 'undefined') {
	const style = document.createElement('style');
	style.textContent = hideFormTokenFieldHelp;
	document.head.appendChild(style);
}

const theme = createTheme({
	components: {
		MuiButtonBase: {
			defaultProps: {
				disableRipple: true
			}
		}
	}
});

// Default Theme Preview Component
class DefaultThemePreview extends Component {
	state = {
		currentTab: 0
	};

	render() {
		const { currentTab } = this.state;
		const { showLocation, showStaff, customUserFields = [] } = this.props;

		const tabs = [
			...(showLocation ? [{ label: 'Location', icon: LocationIcon, iconSelected: LocationIcon, id: 'location' }] : []),
			{ label: 'Service', icon: ServiceIcon, iconSelected: ServiceIcon, id: 'service' },
			...(showStaff ? [{ label: 'Staff', icon: StaffIcon, iconSelected: StaffIcon, id: 'staff' }] : []),
			{ label: 'Date & Time', icon: DateIcon, iconSelected: DateIcon, id: 'datetime' },
			{ label: 'Your Information', icon: InfoIcon, iconSelected: InfoIcon, id: 'userinfo' },
			{ label: 'Payments', icon: PaymentIcon, iconSelected: PaymentIcon, id: 'payments' },
			{ label: 'Confirmation', icon: ConfirmIcon, iconSelected: ConfirmIcon, id: 'confirmation' }
		];

		const tabTitles = [
			...(showLocation ? ['Select Location'] : []),
			'Select Service',
			...(showStaff ? ['Select Staff'] : []),
			'Date & Time',
			'Your Information',
			'Payments',
			'Confirmation'
		];

		return (
			<ThemeProvider theme={theme}>
				<CssBaseline />
				<Box sx={{ maxWidth: 1000, mx: 'auto' }}>
					<Stack direction="row" spacing={0} sx={{ borderRadius: 2, overflow: 'hidden' }}>
						<Box sx={{ minWidth: 200, height: 561, bgcolor: '#042626', p: '12px 6px', color: '#fff', borderRadius: '12px 0 0 12px', display: 'flex', flexDirection: 'column' }}>
							<List dense disablePadding>
								{tabs.map((tab, index) => {
									const isActive = currentTab === index;
									return (
										<ListItem key={index} disablePadding>
											<ListItemButton onClick={() => this.setState({ currentTab: index })} sx={{ borderRadius: 1, py: 1.2 }} selected={isActive}>
												<ListItemIcon sx={{ height: 30, minWidth: 40 }}>
													<Box component="img" src={isActive ? tab.iconSelected : tab.icon} alt={`${tab.label} icon`} />
												</ListItemIcon>
												<ListItemText primaryTypographyProps={{ fontSize: 14, fontWeight: 700, color: isActive ? '#FFFFFF' : '#96B8B8' }} primary={tab.label} />
											</ListItemButton>
										</ListItem>
									);
								})}
							</List>
							<Box sx={{ mt: 'auto', color: 'rgba(255,255,255,0.85)', fontSize: 13, px: 1.5 }}>
								<Typography sx={{ opacity: 0.6, textAlign: 'center', padding: '10px' }}>Need Help?</Typography>
							</Box>
						</Box>

						<Paper variant="outlined" sx={{ minHeight: 561, borderColor: '#E6F2F1', bgcolor: '#ffffff', borderRadius: '0 12px 12px 0', flex: 1, display: 'flex', flexDirection: 'column' }}>
							<Box sx={{ bgcolor: '#f2fbfa', borderBottom: '1px solid #E6F2F1', p: 2.25, borderRadius: '0 12px 0 0', color: '#21403f', fontWeight: 600 }}>
								<Typography fontWeight={700} color="#587373" fontSize="20px">
									{tabTitles[currentTab]}
								</Typography>
							</Box>

							<Box sx={{ minHeight: 300, p: 2.25, flex: 1 }}>
								{showLocation && currentTab === 0 && (
									<Box>
										<Stack direction="row" spacing={1.5} alignItems="center" sx={{ border: '1px solid #B8D9D9', borderRadius: 1.5, px: 2, py: 1.5, maxWidth: 260 }}>
											<Avatar sx={{ width: 36, height: 36, bgcolor: '#e7eeed', color: '#6a7f7d' }}>
												<PersonOutlined />
											</Avatar>
											<Typography color="#587373" fontWeight={700}>Default Location</Typography>
										</Stack>
									</Box>
								)}

								{currentTab === (showLocation ? 1 : 0) && (
									<Box>
										<Typography variant="subtitle1" sx={{ mb: 1.5, textTransform: 'none' }} color="#21403f" fontWeight={400}>Service</Typography>
										<Stack direction="row" spacing={1.5} alignItems="center" sx={{ border: '1px solid #B8D9D9', borderRadius: 1.5, px: 2, py: 1.5, maxWidth: 260 }}>
											<Avatar sx={{ width: 36, height: 36, bgcolor: '#e7eeed', color: '#6a7f7d' }}>
												<PersonOutlined />
											</Avatar>
											<Typography color="#587373" fontWeight={700}>Skin</Typography>
										</Stack>
									</Box>
								)}

								{showStaff && currentTab === (showLocation ? 2 : 1) && (
									<Box>
										<Stack direction="row" spacing={1.5} alignItems="center" sx={{ border: '1px solid #B8D9D9', borderRadius: 1.5, px: 2, py: 1.5, maxWidth: 260 }}>
											<Avatar sx={{ width: 36, height: 36, bgcolor: '#e7eeed', color: '#6a7f7d' }}>
												<PersonOutlined />
											</Avatar>
											<Typography color="#587373" fontWeight={700}>John Doe <br /> john@gmail.com </Typography>
										</Stack>
									</Box>
								)}

								{currentTab === (showStaff ? 3 : showLocation ? 2 : 1) && (
									<Box>
										<Typography variant="subtitle1" sx={{ mb: 1.5, textTransform: 'none' }} color="text.secondary">Select Appointment</Typography>
										<Paper variant="outlined" sx={{ p: 2.5, textAlign: 'center', bgcolor: '#f8f9fa' }}>
											<CalendarMonthOutlined sx={{ fontSize: 48, color: '#3498db', mb: 2 }} />
											<Typography variant="body2" color="text.secondary">Calendar and time slots will appear here</Typography>
										</Paper>
									</Box>
								)}

								{currentTab === (showStaff ? 4 : showLocation ? 3 : 2) && (
									<InformationStepPreview customUserFields={customUserFields} />
								)}

								{currentTab === (showStaff ? 5 : showLocation ? 4 : 3) && (
									<Box>
										<Typography variant="subtitle1" sx={{ mb: 1.5, textTransform: 'none' }} color="text.secondary">Payment Method</Typography>
										<Paper variant="outlined" sx={{ p: 2.5, textAlign: 'center', bgcolor: '#f8f9fa', borderStyle: 'dashed' }}>
											<PaymentOutlined sx={{ fontSize: 48, color: '#3498db', mb: 2 }} />
											<Typography variant="body2" color="text.secondary">Payment options will appear here</Typography>
										</Paper>
									</Box>
								)}

								{currentTab === (showStaff ? 6 : showLocation ? 5 : 4) && (
									<Box>
										<Typography variant="subtitle1" sx={{ mb: 1.5, textTransform: 'none' }} color="text.secondary">Booking Summary</Typography>
										<Paper variant="outlined" sx={{ p: 2.5, textAlign: 'center', bgcolor: '#f8f9fa', borderStyle: 'dashed' }}>
											<DoneOutlined sx={{ fontSize: 48, color: '#27ae60', mb: 2 }} />
											<Typography variant="body2" color="text.secondary">Confirmation details will appear here</Typography>
										</Paper>
									</Box>
								)}
							</Box>

							<Box sx={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 1, p: 2, borderTop: '1px solid #E6F2F1', bgcolor: '#f2fbfa', borderRadius: '0 0 12px 0' }}>
								{currentTab > 0 && (
									<Button variant="outlined" sx={{ border: 'none', color: '#21403f', padding: '4px 14px', textTransform: 'none', fontWeight: 400, ":hover": { border: 'none', bgcolor: 'transparent' } }} onClick={() => this.setState({ currentTab: Math.max(0, currentTab - 1) })}>
										Back
									</Button>
								)}
								<Button variant="contained" sx={{ bgcolor: '#036666', padding: '4px 14px', textTransform: 'none', fontWeight: 400, ":hover": { bgcolor: '#0c6f67' } }} disabled={currentTab === (showStaff ? 6 : showLocation ? 5 : 4)} onClick={() => this.setState({ currentTab: Math.min(showStaff ? 6 : showLocation ? 5 : 4, currentTab + 1) })}>
									Next
								</Button>
							</Box>
						</Paper>
					</Stack>
				</Box>
			</ThemeProvider>
		);
	}
}

// Light Theme Preview Component
class LightThemePreview extends Component {
	state = {
		currentStep: 0
	};

	render() {
		const { currentStep } = this.state;
		const { showLocation, showStaff, customUserFields = [] } = this.props;

		const steps = [];
		let stepId = 0;

		if (showLocation) {
			steps.push({ id: stepId++, label: 'Location', title: 'Select Location' });
		}
		steps.push({ id: stepId++, label: 'Service', title: 'Service' });
		if (showStaff) {
			steps.push({ id: stepId++, label: 'Staff', title: 'Select Staff' });
		}
		steps.push({ id: stepId++, label: 'Date & Time', title: 'Date & Time' });
		steps.push({ id: stepId++, label: 'Your Information', title: 'Your Information' });
		steps.push({ id: stepId++, label: 'Payments', title: 'Payments' });
		steps.push({ id: stepId++, label: 'Confirmation', title: 'Booking Successful' });

		const currentStepIndex = steps.findIndex(s => s.id === currentStep);
		const currentStepData = steps[currentStepIndex] || steps[0];
		const isLastStep = currentStep === steps[steps.length - 1].id;

		return (
			<Box sx={{
				width: '45rem',
				maxWidth: '100%',
				bgcolor: 'white',
				borderRadius: '8px',
				boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
				overflow: 'hidden',
				display: 'flex',
				flexDirection: 'row',
				height: '566px',
				border: '1px solid #f1f5f9'
			}}>
				{/* Sidebar */}
				<Box sx={{
					width: '200px',
					maxWidth: '200px',
					bgcolor: '#f8fafc',
					borderRight: '1px solid #f1f5f9',
					display: 'flex',
					flexDirection: 'column',
					py: '12px',
					px: '6px',
					gap: '32px'
				}}>
					<Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', gap: '8px' }}>
						{steps.map((step, index) => {
							const isActive = step.id === currentStep;
							const isPast = currentStep > step.id;
							const getIcon = () => {
								if (step.label === 'Location') return <PersonOutlined sx={{ fontSize: 18 }} />;
								if (step.label === 'Service') return <PersonOutlined sx={{ fontSize: 18 }} />;
								if (step.label === 'Staff') return <PersonOutlined sx={{ fontSize: 18 }} />;
								if (step.label === 'Date & Time') return <CalendarMonthOutlined sx={{ fontSize: 18 }} />;
								if (step.label === 'Your Information') return <PersonOutlineOutlined sx={{ fontSize: 18 }} />;
								if (step.label === 'Payments') return <PaymentOutlined sx={{ fontSize: 18 }} />;
								if (step.label === 'Confirmation') return <DoneOutlined sx={{ fontSize: 18 }} />;
								return <PersonOutlined sx={{ fontSize: 18 }} />;
							};
							return (
								<Box
									key={step.id}
									onClick={() => this.setState({ currentStep: step.id })}
									sx={{
										display: 'flex',
										alignItems: 'center',
										borderRadius: '12px',
										padding: '4px',
										cursor: 'pointer',
										transition: 'all 0.4s',
										...(isActive ? {
											bgcolor: 'white',
											color: '#2563eb',
											boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
											transform: 'scale(1)'
										} : {
											color: '#64748b',
											'&:hover': { bgcolor: '#f1f5f9' }
										})
									}}
								>
									<Box sx={{ display: 'flex', alignItems: 'center', gap: '12px', width: '100%' }}>
										<Box sx={{
											padding: '8px',
											borderRadius: '8px',
											color: isPast && !isActive ? '#2563eb' : 'inherit'
										}}>
											{getIcon()}
										</Box>
										<Typography sx={{
											fontWeight: 500,
											fontSize: '14px',
											flex: 1
										}}>
											{step.label}
										</Typography>
										{isPast && !isActive && (
											<CheckCircle sx={{ fontSize: 12, color: '#2563eb', ml: 'auto' }} />
										)}
									</Box>
								</Box>
							);
						})}
					</Box>

					<Box sx={{
						display: 'flex',
						alignItems: 'center',
						justifyContent: 'center',
						gap: '8px',
						color: '#94a3b8',
						'&:hover': { color: '#2563eb' },
						cursor: 'pointer',
						transition: 'colors',
						px: '12px',
						py: '8px',
						fontSize: '14px',
						fontWeight: 500
					}}>
						<PersonOutlineOutlined sx={{ fontSize: 18 }} />
						<Typography>Need Help?</Typography>
					</Box>
				</Box>

				{/* Main Content */}
				<Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', bgcolor: 'white' }}>
					{/* Header */}
					<Box sx={{
						px: '20px',
						py: '21px',
						borderBottom: '1px solid #f1f5f9',
						display: 'flex',
						justifyContent: 'space-between',
						alignItems: 'center'
					}}>
						<Typography sx={{
							fontSize: '24px',
							fontWeight: 600,
							color: '#334155'
						}}>
							{isLastStep ? 'Booking Successful' : currentStepData.title}
						</Typography>
						{!isLastStep && (
							<Typography sx={{
								fontSize: '12px',
								fontWeight: 600,
								color: '#94a3b8'
							}}>
								{__('Step', 'bookify')} {currentStepIndex + 1} {__('of', 'bookify')} {Math.max(steps.length - 1, 1)}
							</Typography>
						)}
					</Box>

					{/* Body */}
					<Box sx={{
						flex: 1,
						overflowY: 'auto',
						display: 'flex',
						flexDirection: 'column',
						p: '20px'
					}}>
						<Box sx={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
							{currentStepData.label === 'Location' && (
								<Box>
									<Stack direction="row" spacing={1.5} alignItems="center" sx={{ border: '1px solid #e2e8f0', borderRadius: '12px', px: 2, py: 1.5, maxWidth: 260 }}>
										<Avatar sx={{ width: 36, height: 36, bgcolor: '#f1f5f9', color: '#64748b' }}>
											<PersonOutlined />
										</Avatar>
										<Typography sx={{ color: '#334155', fontWeight: 600 }}>Default Location</Typography>
									</Stack>
								</Box>
							)}

							{currentStepData.label === 'Service' && (
								<Box>
									<Typography sx={{ mb: 1.5, color: '#64748b', fontSize: '14px' }}>Service</Typography>
									<Stack direction="row" spacing={1.5} alignItems="center" sx={{ border: '1px solid #e2e8f0', borderRadius: '12px', px: 2, py: 1.5, maxWidth: 260 }}>
										<Avatar sx={{ width: 36, height: 36, bgcolor: '#f1f5f9', color: '#64748b' }}>
											<PersonOutlined />
										</Avatar>
										<Typography sx={{ color: '#334155', fontWeight: 600 }}>Skin</Typography>
									</Stack>
								</Box>
							)}

							{currentStepData.label === 'Staff' && (
								<Box>
									<Stack direction="row" spacing={1.5} alignItems="center" sx={{ border: '1px solid #e2e8f0', borderRadius: '12px', px: 2, py: 1.5, maxWidth: 260 }}>
										<Avatar sx={{ width: 36, height: 36, bgcolor: '#f1f5f9', color: '#64748b' }}>
											<PersonOutlined />
										</Avatar>
										<Typography sx={{ color: '#334155', fontWeight: 600 }}>John Doe<br />john@gmail.com</Typography>
									</Stack>
								</Box>
							)}

							{currentStepData.label === 'Date & Time' && (
								<Box>
									<Typography sx={{ mb: 1.5, color: '#64748b', fontSize: '14px' }}>Select Appointment</Typography>
									<Paper variant="outlined" sx={{ p: 2.5, textAlign: 'center', bgcolor: '#f8fafc', border: '1px solid #e2e8f0' }}>
										<CalendarMonthOutlined sx={{ fontSize: 48, color: '#3b82f6', mb: 2 }} />
										<Typography variant="body2" sx={{ color: '#64748b' }}>Calendar and time slots will appear here</Typography>
									</Paper>
								</Box>
							)}

							{currentStepData.label === 'Your Information' && (
								<InformationStepPreview customUserFields={customUserFields} />
							)}

							{currentStepData.label === 'Payments' && (
								<Box>
									<Typography sx={{ mb: 1.5, color: '#64748b', fontSize: '14px' }}>Payment Method</Typography>
									<Paper variant="outlined" sx={{ p: 2.5, textAlign: 'center', bgcolor: '#f8fafc', border: '1px dashed #e2e8f0' }}>
										<PaymentOutlined sx={{ fontSize: 48, color: '#3b82f6', mb: 2 }} />
										<Typography variant="body2" sx={{ color: '#64748b' }}>Payment options will appear here</Typography>
									</Paper>
								</Box>
							)}

							{currentStepData.label === 'Confirmation' && (
								<Box>
									<Typography sx={{ mb: 1.5, color: '#64748b', fontSize: '14px' }}>Booking Summary</Typography>
									<Paper variant="outlined" sx={{ p: 2.5, textAlign: 'center', bgcolor: '#f8fafc', border: '1px dashed #e2e8f0' }}>
										<DoneOutlined sx={{ fontSize: 48, color: '#10b981', mb: 2 }} />
										<Typography variant="body2" sx={{ color: '#64748b' }}>Confirmation details will appear here</Typography>
									</Paper>
								</Box>
							)}
						</Box>
					</Box>

					{/* Navigation Buttons */}
					<Box sx={{
						display: 'flex',
						justifyContent: 'flex-end',
						alignItems: 'center',
						gap: 2,
						px: '20px',
						py: '16px',
						borderTop: '1px solid #f1f5f9',
						bgcolor: 'white'
					}}>
						{currentStepIndex > 0 && (
							<Button
								variant="outlined"
								onClick={() => {
									const prevStep = steps[currentStepIndex - 1];
									if (prevStep) this.setState({ currentStep: prevStep.id });
								}}
								sx={{
									textTransform: 'none',
									fontWeight: 500,
									color: '#64748b',
									borderColor: '#e2e8f0',
									'&:hover': {
										bgcolor: '#f8fafc',
										borderColor: '#cbd5e1'
									}
								}}
							>
								Back
							</Button>
						)}
						<Button
							variant="contained"
							disabled={isLastStep}
							onClick={() => {
								const nextStep = steps[currentStepIndex + 1];
								if (nextStep) this.setState({ currentStep: nextStep.id });
							}}
							sx={{
								textTransform: 'none',
								fontWeight: 500,
								bgcolor: '#2563eb',
								color: 'white',
								boxShadow: 'none',
								'&:hover': {
									bgcolor: '#1d4ed8',
									boxShadow: 'none'
								}
							}}
						>
							Next
						</Button>
					</Box>
				</Box>
			</Box>
		);
	}
}

const BookingFormBlock = ({ attributes, setAttributes }) => {
	const { theme, locations, hide_locations, services, hide_services, staffs, hide_staffs, blockTitle, blockDescription, backgroundColor, textColor, customUserFields = [] } = attributes;

	const [locationOptions, setLocationOptions] = useState([]);
	const [serviceOptions, setServiceOptions] = useState([]);
	const [staffOptions, setStaffOptions] = useState([]);
	const [loading, setLoading] = useState(true);
	const [errors, setErrors] = useState({});

	// Normalize API options to a consistent shape: { id, label } so block works with
	// either Blocks API (id, name) or main REST (service_id, service_name, etc.)
	const normalizeOptions = (arr, labelKey) => {
		if (!Array.isArray(arr)) return [];
		return arr.map((o) => {
			const id = o.service_id ?? o.id ?? o.location_id;
			const label = o[labelKey] ?? o.name ?? (id ? String(id) : '');
			return { ...o, id: id != null ? String(id) : '', label: String(label || '') };
		}).filter((o) => o.id !== '');
	};

	const fetchData = async (endpoint, setter, errorKey, labelKey) => {
		const headers = {
			'X-WP-Nonce': window?.bookifyBlocks?.nonce || '',
			'Content-Type': 'application/json'
		};

		try {
			const response = await fetch(endpoint, { headers });
			if (response.ok) {
				const data = await response.json();
				const arrayData = Array.isArray(data) ? data :
					(data?.data && Array.isArray(data.data)) ? data.data :
						(data?.serviceData && Array.isArray(data.serviceData)) ? data.serviceData : [];
				setter(normalizeOptions(arrayData, labelKey));
			} else {
				setErrors(prev => ({ ...prev, [errorKey]: `HTTP ${response.status}` }));
				setter([]);
			}
		} catch (error) {
			setErrors(prev => ({ ...prev, [errorKey]: error.message }));
			setter([]);
		}
	};

	useEffect(() => {
		const loadData = async () => {
			await Promise.all([
				fetchData('/wp-json/bookify/v1/locations', setLocationOptions, 'locations', 'location_name'),
				fetchData('/wp-json/bookify/v1/services', setServiceOptions, 'services', 'service_name'),
				fetchData('/wp-json/bookify/v1/staffs', setStaffOptions, 'staffs', 'staff_name')
			]);
			setLoading(false);
		};

		loadData();
	}, []);

	const getSelectedNames = (selectedIds, options, fieldName) => {
		if (!selectedIds) return [];
		if (selectedIds === 'all') return [__('All', 'bookify')];

		const ids = typeof selectedIds === 'string' ? selectedIds.split(',') : selectedIds;

		// If 'all' is somehow part of an array
		if (ids.includes('all')) return [__('All', 'bookify')];

		return ids.map((id) => {
			const option = options.find((opt) => String(opt.id) === String(id));
			return option ? option[fieldName] : id;
		}).filter(Boolean);
	};

	const getSelectedIds = (selectedNames, options, fieldName) => {
		if (!selectedNames || selectedNames.length === 0) return '';

		const ids = selectedNames.map((token) => {
			const name = typeof token === 'string' ? token : (token?.value || token?.title || String(token));

			// Detect if they selected 'All' specifically
			if (String(name).trim().toLowerCase() === __('All', 'bookify').toLowerCase() || String(name).trim().toLowerCase() === 'all') {
				return 'all';
			}

			const option = options.find((opt) => String(opt[fieldName]).trim().toLowerCase() === String(name).trim().toLowerCase());
			return option ? String(option.id) : null;
		}).filter(Boolean);

		// If 'all' was in the selected badges, return just 'all' string, discarding other specific ids.
		if (ids.includes('all')) {
			return 'all';
		}

		return ids.length > 0 ? ids.join(',') : '';
	};

	const getSuggestions = (options, fieldName) => {
		const suggestions = options.map((option) => option[fieldName]).filter(Boolean);
		suggestions.unshift(__('All', 'bookify')); // Prepend the "All" option to the front of suggestions list
		return suggestions;
	};

	const blockProps = useBlockProps({
		className: 'bookify-block bookify-booking-form'
	});

	const backgroundClass = getColorClassName('background-color', backgroundColor);
	const textClass = getColorClassName('color', textColor);
	const bookifypro = window?.bookifyBlocks?.pro;

	const blockClasses = [
		'bookify-block',
		'bookify-booking-form',
		backgroundClass,
		textClass
	].filter(Boolean).join(' ');

	const blockStyle = {
		backgroundColor: backgroundColor?.color,
		color: textColor?.color
	};

	const renderFormField = (label, errorKey, options, fieldName, selectedValue, onChange, placeholder, hideValue, hideOnChange) => (
		<>
			<label style={{ fontWeight: 'bold', marginBottom: '8px', display: 'block' }}>
				{__(label, 'bookify')}
				{errors[errorKey] && (
					<span style={{ color: 'red', fontSize: '12px' }}>
						- Error: {errors[errorKey]}
					</span>
				)}
			</label>
			<FormTokenField
				value={getSelectedNames(selectedValue, options, fieldName)}
				suggestions={getSuggestions(options, fieldName)}
				onChange={(tokens) => {
					const newIds = getSelectedIds(tokens, options, fieldName);
					onChange(newIds);
				}}
				placeholder={__(placeholder, 'bookify')}
				style={{ marginBottom: '12px' }}
			/>
			<ToggleControl
				label={__(`Hide ${label}`, 'bookify')}
				checked={hideValue === 'true'}
				onChange={hideOnChange}
				style={{ marginBottom: '16px' }}
			/>
		</>
	);

	return (
		<>
			<InspectorControls>
				<PanelBody title={__('Booking Form Settings', 'bookify')} initialOpen={true}>
					<SelectControl
						label={__('Theme', 'bookify')}
						value={theme || 'default'}
						options={[
							{ label: __('Default', 'bookify'), value: 'default' },
							{ label: __('Light', 'bookify'), value: 'light' }
						]}
						onChange={(value) => setAttributes({ theme: value })}
						style={{ marginBottom: '16px' }}
					/>
					{loading && (
						<div style={{ padding: '10px', textAlign: 'center' }}>
							<p>Loading options...</p>
						</div>
					)}

					{!loading && (
						<>
							{renderFormField(
								'Locations',
								'locations',
								locationOptions,
								'label',
								locations,
								(newIds) => setAttributes({ locations: newIds }),
								'Select locations...',
								hide_locations,
								(value) => setAttributes({ hide_locations: value ? 'true' : 'false' })
							)}

							{renderFormField(
								'Services',
								'services',
								serviceOptions,
								'label',
								services,
								(newIds) => setAttributes({ services: newIds }),
								'Select services...',
								hide_services,
								(value) => setAttributes({ hide_services: value ? 'true' : 'false' })
							)}

							{renderFormField(
								'Staff',
								'staffs',
								staffOptions,
								'label',
								staffs,
								(newIds) => setAttributes({ staffs: newIds }),
								'Select staff members...',
								hide_staffs,
								(value) => setAttributes({ hide_staffs: value ? 'true' : 'false' })
							)}
						</>
					)}
				</PanelBody>
				{bookifypro && (
				<PanelBody title={__('Additional Fields', 'bookify')} initialOpen={false}>
					<CustomFieldsInspector
						fields={customUserFields}
						onChange={(fields) => setAttributes({ customUserFields: fields })}
					/>
				</PanelBody>
				)}
			</InspectorControls>

			<Box {...blockProps} className={blockClasses} style={blockStyle}>
				<Box sx={{ bgcolor: '#fff', borderRadius: 1 }}>
					{blockTitle && (
						<Typography variant="h5" sx={{ mb: 1.5 }} color="#333" fontWeight={600}>
							{blockTitle}
						</Typography>
					)}
					{blockDescription && (
						<Typography sx={{ mb: 2 }} color="#666" lineHeight={1.5}>
							{blockDescription}
						</Typography>
					)}
					{(theme === 'light') ? (
					<CustomFieldsProvider customFields={bookifypro ? customUserFields : []}>
						<LightThemePreview
							showLocation={Boolean(window?.bookifyBlocks?.pro)}
							showStaff={Boolean(window?.bookifyBlocks?.pro)}
							customUserFields={bookifypro ? customUserFields : []}
						/>
					</CustomFieldsProvider>
					) : (
					<CustomFieldsProvider customFields={bookifypro ? customUserFields : []}>
						<DefaultThemePreview
							showLocation={Boolean(window?.bookifyBlocks?.pro)}
							showStaff={Boolean(window?.bookifyBlocks?.pro)}
							customUserFields={bookifypro ? customUserFields : []}
						/>
					</CustomFieldsProvider>
					)}
					{!loading && Object.keys(errors).length > 0 && (
						<Box sx={{ fontSize: 11, color: '#999', mt: 1.25, p: 0.75, bgcolor: '#f9f9f9', borderRadius: 0.5 }}>
							<Typography sx={{ color: 'red' }}>Errors: {JSON.stringify(errors)}</Typography>
						</Box>
					)}
				</Box>
			</Box>
		</>
	);
};

export default BookingFormBlock;