/**
 * Staging Site Setup Modal Component.
 *
 * Modal for setting up a staging environment.
 *
 * @package Sideconvo
 */

import { useState } from '@wordpress/element';
import './staging-setup-modal.css';

interface StagingSetupModalProps {
	onConfirm: (stagingUrl: string) => void;
	onCancel: () => void;
}

/**
 * StagingSetupModal component.
 *
 * @param {StagingSetupModalProps} props Component props.
 * @return {JSX.Element} Modal component.
 */
export default function StagingSetupModal({
	onConfirm,
	onCancel,
}: StagingSetupModalProps) {
	const [stagingUrl, setStagingUrl] = useState('');
	const [error, setError] = useState('');

	const validateUrl = (url: string): boolean => {
		if (!url) {
			setError('Please enter a staging site URL');
			return false;
		}

		// Basic URL validation
		const urlPattern = /^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/.*)?$/i;
		if (!urlPattern.test(url)) {
			setError('Please enter a valid URL');
			return false;
		}

		setError('');
		return true;
	};

	const handleConfirm = () => {
		if (validateUrl(stagingUrl)) {
			onConfirm(stagingUrl);
		}
	};

	return (
		<div className="staging-modal__overlay" onClick={onCancel}>
			<div
				className="staging-modal"
				onClick={(e) => e.stopPropagation()}
			>
				<div className="staging-modal__header">
					<h3>Setup Staging Site</h3>
				</div>

				<div className="staging-modal__body">
					<p className="staging-modal__description">
						Add a staging or development environment for testing before
						syncing to your production site.
					</p>

					<div className="staging-modal__field">
						<label htmlFor="staging-url">Staging Site URL</label>
						<input
							id="staging-url"
							type="text"
							className="staging-modal__input"
							value={stagingUrl}
							onChange={(e) => {
								setStagingUrl(e.target.value);
								setError('');
							}}
							placeholder="stage.example.com"
							autoFocus
						/>
						{error && (
							<span className="staging-modal__error">{error}</span>
						)}
					</div>

					<div className="staging-modal__info">
						<span className="staging-modal__info-icon">ℹ️</span>
						<div>
							<p>Your staging site will get its own API key.</p>
							<p>Staging content is kept separate from production.</p>
						</div>
					</div>
				</div>

				<div className="staging-modal__footer">
					<button
						className="staging-modal__button staging-modal__button--secondary"
						onClick={onCancel}
					>
						Cancel
					</button>
					<button
						className="staging-modal__button staging-modal__button--primary"
						onClick={handleConfirm}
					>
						Continue to Sideconvo →
					</button>
				</div>
			</div>
		</div>
	);
}
