import React, { useEffect, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { __, sprintf } from '@wordpress/i18n';
import './deactivation-feedback.css';

function DeactivationFeedback({ config }) {
	const dialog = useRef(null);
	const originalLink = useRef(null);
	const request = useRef(null);
	const timer = useRef(null);
	const submitting = useRef(false);
	const navigating = useRef(false);
	const [reason, setReason] = useState('');
	const [comments, setComments] = useState({});
	const [deactivationUrl, setDeactivationUrl] = useState('');
	const [busy, setBusy] = useState(false);

	useEffect(() => {
		function onDeactivate(event) {
			if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
				return;
			}
			const link = event.target instanceof Element ? event.target.closest('a') : null;
			if (!link || link.target || link.hasAttribute('download') || link.closest('tr[data-plugin]')?.dataset.plugin !== config.pluginFile) {
				return;
			}
			const url = new URL(link.href, window.location.href);
			if (url.origin !== window.location.origin || url.searchParams.get('action') !== 'deactivate' || url.searchParams.get('plugin') !== config.pluginFile) {
				return;
			}
			// Leave the original WordPress link usable if the enhancement cannot open.
			try {
				dialog.current.showModal();
			} catch {
				return;
			}
			event.preventDefault();
			originalLink.current = link;
			setDeactivationUrl(link.href);
			setReason('');
			setComments({});
		}
		document.addEventListener('click', onDeactivate);
		return () => {
			document.removeEventListener('click', onDeactivate);
			window.clearTimeout(timer.current);
			request.current?.abort();
		};
	}, [config]);

	function close() {
		if (!submitting.current) {
			dialog.current.close();
			originalLink.current?.focus();
		}
	}

	function deactivate() {
		if (navigating.current) {
			return;
		}
		navigating.current = true;
		window.clearTimeout(timer.current);
		request.current?.abort();
		window.location.assign(originalLink.current.href);
	}

	function keepFocusInside(event) {
		if (event.key !== 'Tab') {
			return;
		}
		const firstRadio = dialog.current.querySelector('input[type="radio"]');
		const controls = [...dialog.current.querySelectorAll('button:not(:disabled), a[href], input:not(:disabled), textarea:not(:disabled)')]
			.filter((control) => control.type !== 'radio' || control.checked || (!reason && control === firstRadio));
		const first = controls[0];
		const last = controls[controls.length - 1];
		if (event.shiftKey && document.activeElement === first) {
			event.preventDefault();
			last.focus();
		} else if (!event.shiftKey && document.activeElement === last) {
			event.preventDefault();
			first.focus();
		}
	}

	async function submit(event) {
		event.preventDefault();
		if (!reason || submitting.current) {
			return;
		}
		submitting.current = true;
		setBusy(true);
		// Always proceed, even if a mail integration or the AJAX request stalls.
		timer.current = window.setTimeout(deactivate, 8000);
		try {
			request.current = new AbortController();
			await fetch(config.ajaxUrl, {
				method: 'POST',
				credentials: 'same-origin',
				body: new URLSearchParams({
					action: config.action,
					nonce: config.nonce,
					consent: '1',
					reason,
					comment: comments[reason] || '',
				}),
				signal: request.current.signal,
			});
		} catch {
			// Feedback delivery is optional and must never block the native action.
		} finally {
			deactivate();
		}
	}

	return (
		<dialog
			ref={dialog}
			className="adyenDeactivationFeedback"
			aria-labelledby="adyen-feedback-title"
			aria-describedby="adyen-feedback-intro"
			onCancel={(event) => { event.preventDefault(); close(); }}
			onKeyDown={keepFocusInside}
		>
			<h2 id="adyen-feedback-title">{__('Before you deactivate', 'digital-apps-payments-for-adyen')}</h2>
			<p id="adyen-feedback-intro">{__('Help us improve Digital Apps Payments for Adyen. Feedback is optional, and you can always skip it.', 'digital-apps-payments-for-adyen')}</p>
			<form onSubmit={submit}>
				<fieldset disabled={busy} className="adyenDeactivationFeedback__reasons">
					<legend>{__('What made you deactivate the plugin?', 'digital-apps-payments-for-adyen')}</legend>
					{Object.entries(config.reasons).map(([value, option]) => (
						<label key={value} className="adyenDeactivationFeedback__reason">
							<input type="radio" name="adyen-feedback-reason" value={value} checked={reason === value} onChange={() => setReason(value)} />
							<span>{option.label}</span>
						</label>
					))}
				</fieldset>
				{reason && (
					<div className="adyenDeactivationFeedback__comment">
						<label htmlFor="adyen-feedback-comment">{__('Tell us more (optional)', 'digital-apps-payments-for-adyen')}</label>
						<p id="adyen-feedback-prompt">{config.reasons[reason].prompt}</p>
						<textarea
							id="adyen-feedback-comment"
							aria-describedby="adyen-feedback-prompt adyen-feedback-sensitive"
							rows={3}
							maxLength={config.maxCommentLength}
							value={comments[reason] || ''}
							onChange={(event) => setComments({ ...comments, [reason]: event.target.value })}
							disabled={busy}
						/>
						<p id="adyen-feedback-sensitive">{__('Please do not include API keys, passwords, payment details, or customer information.', 'digital-apps-payments-for-adyen')}</p>
					</div>
				)}
				<div className="adyenDeactivationFeedback__privacy">
					<p>{sprintf(
						/* translators: 1: support email address, 2: plugin version. */
						__('By choosing "Send feedback and deactivate", you agree to email your selected reason, optional comment, and plugin version (%2$s) to Digital Apps at %1$s to help improve the plugin.', 'digital-apps-payments-for-adyen'),
						config.recipient, config.version
					)}</p>
					<a href="https://digitalapps.com/privacy-policy/" target="_blank" rel="noreferrer noopener">{__('Digital Apps privacy policy', 'digital-apps-payments-for-adyen')}</a>
				</div>
				<p role="status" className="adyenDeactivationFeedback__status">{busy ? __('Sending feedback, then deactivating. You can still skip the wait.', 'digital-apps-payments-for-adyen') : ''}</p>
				<div className="adyenDeactivationFeedback__actions">
					<button type="submit" className="button button-primary" disabled={!reason || busy}>{__('Send feedback and deactivate', 'digital-apps-payments-for-adyen')}</button>
					<a className="button" href={deactivationUrl} onClick={() => { navigating.current = true; window.clearTimeout(timer.current); request.current?.abort(); }}>{__('Skip and deactivate', 'digital-apps-payments-for-adyen')}</a>
					<button type="button" className="button" onClick={close} disabled={busy}>{__('Cancel', 'digital-apps-payments-for-adyen')}</button>
				</div>
			</form>
		</dialog>
	);
}

const config = window.DigitalAppsAdyenDeactivationFeedback;
if (config && typeof HTMLDialogElement !== 'undefined' && typeof HTMLDialogElement.prototype.showModal === 'function') {
	const container = document.createElement('div');
	document.body.appendChild(container);
	createRoot(container).render(<DeactivationFeedback config={config} />);
}
