/**
 * Open Button Settings Component
 *
 * @package Everyone_Accessibility_Suite
 */

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

/**
 * Number inputs hand back '' when cleared, and parseInt('') is NaN - which
 * serialises to null and used to make the whole save request fail validation.
 */
const toInt = (value, fallback = 0) => {
	const parsed = parseInt(value, 10);
	return Number.isNaN(parsed) ? fallback : parsed;
};

const OpenButtonSettings = ({ settings, onSave, saving }) => {
	const [localSettings, setLocalSettings] = useState({
		show_open_button: settings?.show_open_button ?? true,
		button_tabindex: settings?.button_tabindex ?? 0,
		button_position: settings?.button_position ?? 'bottom-right',
		button_caption: settings?.button_caption ?? '',
		button_icon: settings?.button_icon ?? 'default',
		button_icon_position: settings?.button_icon_position ?? 'before',
		button_size: settings?.button_size ?? 24,
		button_margin: settings?.button_margin ?? 10,
		button_padding: settings?.button_padding ?? 20,
		button_border_radius: settings?.button_border_radius ?? 50,
		button_color: settings?.button_color ?? '#ffffff',
		button_color_hover: settings?.button_color_hover ?? '#216ff3',
		button_bgcolor: settings?.button_bgcolor ?? '#216ff3',
		button_bgcolor_hover: settings?.button_bgcolor_hover ?? '#ffffff',
		button_entrance_timeout: settings?.button_entrance_timeout ?? 0,
		button_entrance_animation: settings?.button_entrance_animation ?? 'fade',
		button_hover_animation: settings?.button_hover_animation ?? 'none',
		button_show_after_scrolling_desktop: settings?.button_show_after_scrolling_desktop ?? 0,
		button_show_after_scrolling_mobile: settings?.button_show_after_scrolling_mobile ?? 0,
	});

	const [iconPickerOpen, setIconPickerOpen] = useState(false);

	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 Open Button 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 || '',
				},
				// Scoped: this button used to wipe the Modal Popup tab too,
				// though its confirmation only mentioned the Open Button.
				body: JSON.stringify({ scope: 'button' }),
			});

			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: 'top-left', label: __( 'Top Left', 'everyone-accessibility-suite' ) },
		{ value: 'top-right', label: __( 'Top Right', 'everyone-accessibility-suite' ) },
		{ value: 'left-center', label: __( 'Left Center', 'everyone-accessibility-suite' ) },
		{ value: 'right-center', label: __( 'Right Center', 'everyone-accessibility-suite' ) },
		{ value: 'bottom-left', label: __( 'Bottom Left', 'everyone-accessibility-suite' ) },
		{ value: 'bottom-center', label: __( 'Bottom Center', 'everyone-accessibility-suite' ) },
		{ value: 'bottom-right', label: __( 'Bottom Right', 'everyone-accessibility-suite' ) },
	];

	const iconPositionOptions = [
		{ value: 'none', label: __( 'Hide', 'everyone-accessibility-suite' ) },
		{ value: 'before', label: __( 'Before', 'everyone-accessibility-suite' ) },
		{ value: 'after', label: __( 'After', 'everyone-accessibility-suite' ) },
		{ value: 'above', label: __( 'Above', 'everyone-accessibility-suite' ) },
		{ value: 'bellow', label: __( 'Bellow', 'everyone-accessibility-suite' ) },
	];

	const animationOptions = [
		{ value: 'none', label: __( 'None', 'everyone-accessibility-suite' ) },
		{ value: 'bounce', label: __( 'Bounce', 'everyone-accessibility-suite' ) },
		{ value: 'fade', label: __( 'Fade', 'everyone-accessibility-suite' ) },
		{ value: 'flip-x', label: __( 'Flip X', 'everyone-accessibility-suite' ) },
		{ value: 'flip-y', label: __( 'Flip Y', 'everyone-accessibility-suite' ) },
		{ value: 'scale', label: __( 'Scale', 'everyone-accessibility-suite' ) },
		{ value: 'wobble', label: __( 'Wobble', 'everyone-accessibility-suite' ) },
		{ value: 'rotate', label: __( 'Rotate', '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">{__( 'Show Open Button', 'everyone-accessibility-suite' )}</th>
								<td>
									<label className="evas-toggle-switch">
										<input
											type="checkbox"
											checked={localSettings.show_open_button}
											onChange={(e) => handleChange('show_open_button', e.target.checked)}
										/>
										<span className="evas-toggle-slider"></span>
									</label>
								</td>
							</tr>

							<tr>
								<th scope="row"><label>{__( 'Position', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<select
										value={localSettings.button_position}
										onChange={(e) => handleChange('button_position', e.target.value)}
										className="regular-text"
									>
										{positionOptions.map(option => (
											<option key={option.value} value={option.value}>
												{option.label}
											</option>
										))}
									</select>
								</td>
							</tr>

							<tr>
								<th scope="row"><label>{__( 'Tabulation Index', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<input
										type="number"
										min="-1"
										max="3"
										value={localSettings.button_tabindex}
										onChange={(e) => handleChange('button_tabindex', toInt(e.target.value))}
										className="small-text"
									/>
									<p className="evas-field-description">{__( 'Tabulation index:', 'everyone-accessibility-suite' )} {localSettings.button_tabindex}</p>
								</td>
							</tr>

							<tr>
								<th scope="row"><label>{__( 'Caption', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<input
										type="text"
										value={localSettings.button_caption}
										onChange={(e) => handleChange('button_caption', e.target.value)}
										maxLength="4500"
										className="regular-text"
									/>
									<p className="evas-field-description">{__( 'Button caption text', 'everyone-accessibility-suite' )}</p>
								</td>
							</tr>

							<tr>
								<th scope="row"><label>{__( 'Icon', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<button
										type="button"
										className="button"
										onClick={() => setIconPickerOpen(true)}
									>
										{__( 'Select Icon:', 'everyone-accessibility-suite' )} {localSettings.button_icon}
									</button>
								</td>
							</tr>

							<tr>
								<th scope="row"><label>{__( 'Icon Position', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<select
										value={localSettings.button_icon_position}
										onChange={(e) => handleChange('button_icon_position', e.target.value)}
										className="regular-text"
									>
										{iconPositionOptions.map(option => (
											<option key={option.value} value={option.value}>
												{option.label}
											</option>
										))}
									</select>
								</td>
							</tr>
						</tbody>
					</table>
				</div>

				{/* Size Settings */}
				<div className="evas-settings-section">
					<h3>{__( 'Size Settings', 'everyone-accessibility-suite' )}</h3>

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

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

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

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

				{/* Color Settings */}
				<div className="evas-settings-section">
					<h3>{__( 'Color Settings', 'everyone-accessibility-suite' )}</h3>

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

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

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

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

				{/* Animation Settings */}
				<div className="evas-settings-section">
					<h3>{__( 'Animation Settings', 'everyone-accessibility-suite' )}</h3>

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

							<tr>
								<th scope="row"><label>{__( 'Entrance Animation', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<select
										value={localSettings.button_entrance_animation}
										onChange={(e) => handleChange('button_entrance_animation', e.target.value)}
										className="regular-text"
									>
										{animationOptions.map(option => (
											<option key={option.value} value={option.value}>
												{option.label}
											</option>
										))}
									</select>
								</td>
							</tr>

							<tr>
								<th scope="row"><label>{__( 'Hover Animation', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<select
										value={localSettings.button_hover_animation}
										onChange={(e) => handleChange('button_hover_animation', e.target.value)}
										className="regular-text"
									>
										{animationOptions.map(option => (
											<option key={option.value} value={option.value}>
												{option.label}
											</option>
										))}
									</select>
								</td>
							</tr>
						</tbody>
					</table>
				</div>

				{/* Scroll Settings */}
				<div className="evas-settings-section">
					<h3>{__( 'Show After Scrolling', 'everyone-accessibility-suite' )}</h3>

					<table className="form-table">
						<tbody>
							<tr>
								<th scope="row"><label>{__( 'For Desktop Devices', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<input
										type="range"
										min="0"
										max="300"
										step="10"
										value={localSettings.button_show_after_scrolling_desktop}
										onChange={(e) => handleChange('button_show_after_scrolling_desktop', toInt(e.target.value))}
										style={{ width: '300px' }}
									/>
									<span className="evas-range-value">{localSettings.button_show_after_scrolling_desktop}px</span>
									<p className="evas-field-description">{__( 'Define how many pixels the user must scroll before the Open Button appears', 'everyone-accessibility-suite' )}</p>
								</td>
							</tr>

							<tr>
								<th scope="row"><label>{__( 'For Mobile Devices', 'everyone-accessibility-suite' )}</label></th>
								<td>
									<input
										type="range"
										min="0"
										max="300"
										step="10"
										value={localSettings.button_show_after_scrolling_mobile}
										onChange={(e) => handleChange('button_show_after_scrolling_mobile', toInt(e.target.value))}
										style={{ width: '300px' }}
									/>
									<span className="evas-range-value">{localSettings.button_show_after_scrolling_mobile}px</span>
								</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>

			<IconPicker
				open={iconPickerOpen}
				onClose={() => setIconPickerOpen(false)}
				onSelect={(icon) => handleChange('button_icon', icon.id)}
				currentIcon={localSettings.button_icon}
			/>
		</div>
	);
};

export default OpenButtonSettings;
