/**
 * Modal Popup Settings Component
 *
 * @package Everyone_Accessibility_Suite
 */

import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * See OpenButtonSettings: an emptied number field yields NaN, which used to
 * be serialised as null and rejected by the REST schema.
 */
const toInt = (value, fallback = 0) => {
	const parsed = parseInt(value, 10);
	return Number.isNaN(parsed) ? fallback : parsed;
};

const ModalPopupSettings = ({ settings, onSave, saving }) => {
	const [localSettings, setLocalSettings] = useState({
		popup_position: settings?.popup_position ?? 'right',
		popup_draggable: settings?.popup_draggable ?? true,
		popup_theme_mode: settings?.popup_theme_mode ?? 'auto',
		popup_background_color: settings?.popup_background_color ?? '#ffffff',
		popup_key_color: settings?.popup_key_color ?? '#216ff3',
		popup_text_color: settings?.popup_text_color ?? '#333333',
		popup_background_color_dark: settings?.popup_background_color_dark ?? '#16191b',
		popup_key_color_dark: settings?.popup_key_color_dark ?? '#216ff3',
		popup_text_color_dark: settings?.popup_text_color_dark ?? '#deeffd',
		popup_border_radius: settings?.popup_border_radius ?? 20,
		popup_shadow: settings?.popup_shadow ?? true,
		popup_overlay: settings?.popup_overlay ?? false,
		popup_overlay_color: settings?.popup_overlay_color ?? '#0253ee',
		popup_close_anywhere: settings?.popup_close_anywhere ?? false,
		reset_button: settings?.reset_button ?? true,
		hide_button: settings?.hide_button ?? true,
	});

	const handleChange = (field, value) => {
		setLocalSettings(prev => ({ ...prev, [field]: value }));
	};

	const handleSave = async (e) => {
		e.preventDefault();
		await onSave(localSettings);
	};

	const handleReset = async () => {
		if (!confirm(__( 'Are you sure you want to reset all Modal Popup settings to their defaults?', 'everyone-accessibility-suite' ))) {
			return;
		}

		try {
			const response = await fetch('/wp-json/evas/v1/customizer/reset', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					'X-WP-Nonce': window.evasAdmin?.nonce || '',
				},
				// Only this tab, matching what the confirmation promises.
				body: JSON.stringify({ scope: 'popup' }),
			});

			if (!response.ok) {
				throw new Error('Failed to reset settings');
			}

			const data = await response.json();

			if (data.success && data.data) {
				// The response carries every key of this scope, so merging it
				// is enough - no page reload needed.
				setLocalSettings(prev => ({ ...prev, ...data.data }));
			}
		} catch (error) {
			console.error('Error resetting settings:', error);
			alert(__( 'Error resetting settings', 'everyone-accessibility-suite' ));
		}
	};

	const positionOptions = [
		{ value: 'right', label: __( 'Right', 'everyone-accessibility-suite' ) },
		{ value: 'center', label: __( 'Center', 'everyone-accessibility-suite' ) },
		{ value: 'left', label: __( 'Left', 'everyone-accessibility-suite' ) },
	];

	return (
		<div className="evas-customizer-settings">
			<form onSubmit={handleSave}>
				{/* Basic Settings */}
				<div className="evas-settings-section">
					<h3>{__( 'Basic Settings', 'everyone-accessibility-suite' )}</h3>

					<table className="form-table">
						<tbody>
							<tr>
								<th scope="row"><label>{__( 'Popup Position', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<select
										value={localSettings.popup_position}
										onChange={(e) => handleChange('popup_position', e.target.value)}
										className="regular-text"
									>
										{positionOptions.map(option => (
											<option key={option.value} value={option.value}>
												{option.label}
											</option>
										))}
									</select>
									<p className="evas-field-description">{__( 'Select the initial position of the popup display', 'everyone-accessibility-suite' )}</p>
								</td>
							</tr>

							<tr>
								<th scope="row">{__( 'Draggable', 'everyone-accessibility-suite' )}</th>
								<td>
									<label className="evas-toggle-switch">
										<input
											type="checkbox"
											checked={localSettings.popup_draggable}
											onChange={(e) => handleChange('popup_draggable', e.target.checked)}
										/>
										<span className="evas-toggle-slider"></span>
									</label>
									<p className="evas-field-description">{__( 'Controls dragging popup', 'everyone-accessibility-suite' )}</p>
								</td>
							</tr>

							<tr>
								<th scope="row"><label>{__( 'Theme Mode', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<select
										value={localSettings.popup_theme_mode}
										onChange={(e) => handleChange('popup_theme_mode', e.target.value)}
									>
										<option value="auto">{__( 'Auto (follow visitor’s system)', 'everyone-accessibility-suite' )}</option>
										<option value="light">{__( 'Always Day (Light)', 'everyone-accessibility-suite' )}</option>
										<option value="dark">{__( 'Always Night (Dark)', 'everyone-accessibility-suite' )}</option>
									</select>
									<p className="evas-field-description">
										{__( 'Which color set the panel uses. Auto follows the visitor’s operating system. The panel’s own Dark Contrast feature always overrides this.', 'everyone-accessibility-suite' )}
									</p>
								</td>
							</tr>
						</tbody>
					</table>
				</div>

				{/* Day (Light) Theme */}
				<div className="evas-settings-section">
					<h3>{__( 'Day (Light) Theme', 'everyone-accessibility-suite' )}</h3>
					<p className="evas-field-description">{__( 'Select colors for the Day(Light) theme', 'everyone-accessibility-suite' )}</p>

					<table className="form-table">
						<tbody>
							<tr>
								<th scope="row"><label>{__( 'Background Color', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<input
										type="color"
										value={localSettings.popup_background_color}
										onChange={(e) => handleChange('popup_background_color', e.target.value)}
									/>
								</td>
							</tr>

							<tr>
								<th scope="row"><label>{__( 'Key Color', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<input
										type="color"
										value={localSettings.popup_key_color}
										onChange={(e) => handleChange('popup_key_color', e.target.value)}
									/>
								</td>
							</tr>

							<tr>
								<th scope="row"><label>{__( 'Text Color', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<input
										type="color"
										value={localSettings.popup_text_color}
										onChange={(e) => handleChange('popup_text_color', e.target.value)}
									/>
								</td>
							</tr>
						</tbody>
					</table>
				</div>

				{/* Night (Dark) Theme */}
				<div className="evas-settings-section">
					<h3>{__( 'Night (Dark) Theme', 'everyone-accessibility-suite' )}</h3>
					<p className="evas-field-description">{__( 'Select colors for the Night(Dark) theme', 'everyone-accessibility-suite' )}</p>

					<table className="form-table">
						<tbody>
							<tr>
								<th scope="row"><label>{__( 'Background Color', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<input
										type="color"
										value={localSettings.popup_background_color_dark}
										onChange={(e) => handleChange('popup_background_color_dark', e.target.value)}
									/>
								</td>
							</tr>

							<tr>
								<th scope="row"><label>{__( 'Key Color', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<input
										type="color"
										value={localSettings.popup_key_color_dark}
										onChange={(e) => handleChange('popup_key_color_dark', e.target.value)}
									/>
								</td>
							</tr>

							<tr>
								<th scope="row"><label>{__( 'Text Color', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<input
										type="color"
										value={localSettings.popup_text_color_dark}
										onChange={(e) => handleChange('popup_text_color_dark', e.target.value)}
									/>
								</td>
							</tr>
						</tbody>
					</table>
				</div>

				{/* Appearance and Behavior */}
				<div className="evas-settings-section">
					<h3>{__( 'Appearance and Behavior', 'everyone-accessibility-suite' )}</h3>
					<p className="evas-field-description">{__( 'Set the modal popup appearance and behavior', 'everyone-accessibility-suite' )}</p>

					<table className="form-table">
						<tbody>
							<tr>
								<th scope="row"><label>{__( 'Border Radius', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<input
										type="range"
										min="0"
										max="100"
										value={localSettings.popup_border_radius}
										onChange={(e) => handleChange('popup_border_radius', toInt(e.target.value))}
										style={{ width: '300px' }}
									/>
									<span className="evas-range-value">{localSettings.popup_border_radius}px</span>
								</td>
							</tr>

							<tr>
								<th scope="row">{__( 'Popup Shadow', 'everyone-accessibility-suite' )}</th>
								<td>
									<label className="evas-toggle-switch">
										<input
											type="checkbox"
											checked={localSettings.popup_shadow}
											onChange={(e) => handleChange('popup_shadow', e.target.checked)}
										/>
										<span className="evas-toggle-slider"></span>
									</label>
									<p className="evas-field-description">{__( 'Show popup shadow', 'everyone-accessibility-suite' )}</p>
								</td>
							</tr>

							<tr>
								<th scope="row">{__( 'Overlay', 'everyone-accessibility-suite' )}</th>
								<td>
									<label className="evas-toggle-switch">
										<input
											type="checkbox"
											checked={localSettings.popup_overlay}
											onChange={(e) => handleChange('popup_overlay', e.target.checked)}
										/>
										<span className="evas-toggle-slider"></span>
									</label>
									<p className="evas-field-description">{__( 'Show overlay layer', 'everyone-accessibility-suite' )}</p>
								</td>
							</tr>

							<tr>
								<th scope="row"><label>{__( 'Overlay Color', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<input
										type="color"
										value={localSettings.popup_overlay_color}
										onChange={(e) => handleChange('popup_overlay_color', e.target.value)}
										disabled={!localSettings.popup_overlay}
									/>
								</td>
							</tr>

							<tr>
								<th scope="row">{__( 'Close Anywhere', 'everyone-accessibility-suite' )}</th>
								<td>
									<label className="evas-toggle-switch">
										<input
											type="checkbox"
											checked={localSettings.popup_close_anywhere}
											onChange={(e) => handleChange('popup_close_anywhere', e.target.checked)}
										/>
										<span className="evas-toggle-slider"></span>
									</label>
									<p className="evas-field-description">{__( 'Close by clicking outside the popup', 'everyone-accessibility-suite' )}</p>
								</td>
							</tr>

							<tr>
								<th scope="row">{__( 'Reset Button', 'everyone-accessibility-suite' )}</th>
								<td>
									<label className="evas-toggle-switch">
										<input
											type="checkbox"
											checked={localSettings.reset_button}
											onChange={(e) => handleChange('reset_button', e.target.checked)}
										/>
										<span className="evas-toggle-slider"></span>
									</label>
									<p className="evas-field-description">{__( 'Shows and hides the Reset button', 'everyone-accessibility-suite' )}</p>
								</td>
							</tr>

							<tr>
								<th scope="row">{__( 'Hide Button', 'everyone-accessibility-suite' )}</th>
								<td>
									<label className="evas-toggle-switch">
										<input
											type="checkbox"
											checked={localSettings.hide_button}
											onChange={(e) => handleChange('hide_button', e.target.checked)}
										/>
										<span className="evas-toggle-slider"></span>
									</label>
									<p className="evas-field-description">{__( 'Shows and hides the Hide Forever button', 'everyone-accessibility-suite' )}</p>
								</td>
							</tr>
						</tbody>
					</table>
				</div>

				{/* Save and Reset Buttons */}
				<p className="submit">
					<button
						type="submit"
						className="button button-primary button-large"
						disabled={saving}
						style={{ marginRight: '10px' }}
					>
						{saving ? __( 'Saving...', 'everyone-accessibility-suite' ) : __( 'Save Settings', 'everyone-accessibility-suite' )}
					</button>
					<button
						type="button"
						className="button button-secondary button-large"
						onClick={handleReset}
						disabled={saving}
					>
						{__( 'Reset to Defaults', 'everyone-accessibility-suite' )}
					</button>
				</p>
			</form>
		</div>
	);
};

export default ModalPopupSettings;
