import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { showAlert } from '../utils/alertHelper';
import { openAuthPopup } from '../utils/common';

const AppSetup = ({ clientId, appSecret, redirectUri }) => {
	const [formData, setFormData] = useState({
		client_id: clientId || '',
		client_secret: appSecret || '',
	});
	const [isSaving, setSaving] = useState(false);

	// Copy to clipboard functionality
	const handleCopy = (text) => {
		navigator.clipboard.writeText(text).then(() => {
			showAlert({
				position: 'top-end',
				title: __('Copied!', 'easy-dropbox-integration'),
				icon: 'success',
				showConfirmButton: false,
				toast: true,
				timer: 2000,
				timerProgressBar: true,
			});
		});
	};

	const handleChange = (e) => {
		const { name, value } = e.target;
		setFormData((prev) => ({
			...prev,
			[name]: value,
		}));
	};

	const handleSubmit = async (e) => {
		e.preventDefault();

		if (!formData.client_id || !formData.client_secret) {
			showAlert({
				position: 'top-end',
				title: __('Error', 'easy-dropbox-integration'),
				text: __('Both App Key and App Secret are required.', 'easy-dropbox-integration'),
				icon: 'error',
				showConfirmButton: false,
				toast: true,
				timer: 3000,
				timerProgressBar: true,
			});
			return;
		}

		setSaving(true);

		// Use wp.ajax for the request
		wp.ajax.post('edbi_save_app_setup', {
			edbi_client_id: formData.client_id,
			edbi_client_secret: formData.client_secret,
			nonce: EDBIData.ajaxNonce,
		})
			.done(() => {
				setSaving(false);
				showAlert({
					position: 'top-end',
					title: __('Saved', 'easy-dropbox-integration'),
					text: __('Settings saved successfully! Connecting to Dropbox...', 'easy-dropbox-integration'),
					icon: 'success',
					showConfirmButton: false,
					toast: true,
					timer: 2000,
					timerProgressBar: true,
				});

				// Open Dropbox authorization in popup after a short delay
				// This will fetch a fresh auth URL via AJAX with the new credentials
				setTimeout(() => {
					openAuthPopup('width=700,height=700');
				}, 1000);
			})
			.fail((error) => {
				setSaving(false);
				showAlert({
					position: 'top-end',
					title: __('Error', 'easy-dropbox-integration'),
					text: error.message || __('Failed to save settings.', 'easy-dropbox-integration'),
					icon: 'error',
					showConfirmButton: false,
					toast: true,
					timer: 3000,
					timerProgressBar: true,
				});
			});
	};

	return (
		<div className="wrap">
			<div className="edbi-app-setup__wrapper">
				<div className="edbi-app-setup__card">
					<header className="edbi-app-setup__header">
						<h1>{__('Connect Dropbox', 'easy-dropbox-integration')}</h1>
					</header>

					{/* Info Buttons */}
					<div className="edbi-app-setup__info-buttons">
						<a href="https://ultradevs.com/docs/easy-dropbox-integration/settings/how-to-link-your-own-dropbox-app-with-easy-dropbox-integration-plugin/" target="_blank" rel="noreferrer noopener" className="edbi-info-button edbi-info-button--doc">
							<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
								<path d="M10 2C5.58 2 2 5.58 2 10C2 14.42 5.58 18 10 18C14.42 18 18 14.42 18 10C18 5.58 14.42 2 10 2ZM10 14.5C9.59 14.5 9.25 14.16 9.25 13.75C9.25 13.34 9.59 13 10 13C10.41 13 10.75 13.34 10.75 13.75C10.75 14.16 10.41 14.5 10 14.5ZM11.5 10.38V11H8.5V10.25C8.5 9.97 8.72 9.75 9 9.75H10C10.97 9.75 11.75 8.97 11.75 8C11.75 7.03 10.97 6.25 10 6.25C9.03 6.25 8.25 7.03 8.25 8H7.25C7.25 6.48 8.48 5.25 10 5.25C11.52 5.25 12.75 6.48 12.75 8C12.75 9.21 11.97 10.22 10.88 10.58C10.68 10.65 10.5 10.83 10.5 11.05V10.38H11.5Z" fill="currentColor"/>
							</svg>
							{__('Documentation', 'easy-dropbox-integration')}
						</a>
						<a href="https://ultradevs.com/support/" target="_blank" rel="noreferrer noopener" className="edbi-info-button edbi-info-button--support">
							<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
								<path d="M10 2C5.58 2 2 5.58 2 10C2 14.42 5.58 18 10 18C14.42 18 18 14.42 18 10C18 5.58 14.42 2 10 2ZM10.5 15H9.5V14H10.5V15ZM11.5 11.5C11.5 11.78 11.28 12 11 12H9C8.72 12 8.5 11.78 8.5 11.5V10.5C8.5 10.22 8.72 10 9 10H9.5V6H9C8.72 6 8.5 5.78 8.5 5.5V4.5C8.5 4.22 8.72 4 9 4H11C11.28 4 11.5 4.22 11.5 4.5V10H11C11.28 10 11.5 10.22 11.5 10.5V11.5Z" fill="currentColor"/>
							</svg>
							{__('Get Support', 'easy-dropbox-integration')}
						</a>
						<a href="https://www.youtube.com/watch?v=AzLUtO0EWwI" target="_blank" rel="noreferrer noopener" className="edbi-info-button edbi-info-button--video">
							<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
								<path d="M10 2C5.58 2 2 5.58 2 10C2 14.42 5.58 18 10 18C14.42 18 18 14.42 18 10C18 5.58 14.42 2 10 2ZM7.5 13.5V6.5L13.5 10L7.5 13.5Z" fill="currentColor"/>
							</svg>
							{__('Watch Video', 'easy-dropbox-integration')}
						</a>
						<a href="https://wa.me/8801775605242" target="_blank" rel="noreferrer noopener" className="edbi-info-button edbi-info-button--whatsapp">
							<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
								<path d="M10 2C5.58 2 2 5.58 2 10C2 11.58 2.42 13.08 3.18 14.38L2.25 17.5L5.5 16.6C6.78 17.35 8.25 17.75 9.83 17.75H10C14.42 17.75 18 14.17 18 9.75C18 5.33 14.42 1.75 10 1.75V2ZM13.5 12.5C13.35 12.4 12.58 12 12.44 11.95C12.3 11.9 12.2 11.88 12.09 12.03C11.99 12.18 11.64 12.56 11.55 12.67C11.45 12.78 11.35 12.8 11.2 12.7C11.05 12.6 10.54 12.44 9.94 11.9C9.47 11.48 9.15 10.96 9.05 10.81C8.95 10.66 9.04 10.57 9.14 10.47C9.23 10.38 9.34 10.24 9.44 10.14C9.54 10.04 9.57 9.97 9.63 9.86C9.69 9.75 9.66 9.65 9.62 9.55C9.58 9.45 9.25 8.68 9.13 8.38C9.01 8.09 8.89 8.13 8.8 8.12C8.72 8.11 8.62 8.11 8.52 8.11C8.42 8.11 8.25 8.15 8.11 8.3C7.97 8.45 7.59 8.81 7.59 9.55C7.59 10.29 8.13 11 8.21 11.11C8.29 11.22 9.56 13.14 11.45 13.95C12.58 14.44 12.81 14.34 13.05 14.33C13.29 14.32 13.9 14 14.03 13.67C14.16 13.34 14.16 13.06 14.12 13C14.08 12.94 13.98 12.91 13.83 12.81L13.5 12.5Z" fill="currentColor"/>
							</svg>
							{__('WhatsApp Support', 'easy-dropbox-integration')}
						</a>
					</div>

					<div className="edbi-app-setup__content">
						{/* Left Column: Form */}
						<div className="edbi-app-setup__form-section">
							<div className="edbi-app-setup__banner edbi-badge edbi-badge--info">
								<p className="edbi-app-setup__lead">
									{__('To use Easy Dropbox Integration you need to register a Dropbox app, paste the App Key and App Secret below, and save. That unlocks the rest of the plugin.', 'easy-dropbox-integration')}
								</p>
								<div className="edbi-app-setup__steps">
									<p>{__('Follow these steps before you save:', 'easy-dropbox-integration')}</p>
									<ul>
										<li>
											{__('Create a Dropbox app via the ', 'easy-dropbox-integration')}
											<a href="https://www.dropbox.com/developers/apps" target="_blank" rel="noreferrer noopener">{__('Developer Console', 'easy-dropbox-integration')}</a>
											{__(' and grab the App Key + App Secret.', 'easy-dropbox-integration')}
										</li>
										<li>
											{__('Use ', 'easy-dropbox-integration')}
											<code>{redirectUri}</code>
											{__(' as the Redirect URI so OAuth can return to your dashboard.', 'easy-dropbox-integration')}
										</li>
										<li>{__('Save the App Key/App Secret, reload this page, then connect your Dropbox account from the Settings/File Browser page.', 'easy-dropbox-integration')}</li>
									</ul>
								</div>
							</div>

							<form id="edbi-app-setup-form" className="edbi-app-setup__form" onSubmit={handleSubmit}>
								<div className="edbi-form-group">
									<label htmlFor="edbi_client_id">{__('App Key', 'easy-dropbox-integration')}</label>
									<input
										type="text"
										id="edbi_client_id"
										name="client_id"
										className="edbi-form-input"
										value={formData.client_id}
										onChange={handleChange}
										placeholder={__('Enter your Dropbox App Key', 'easy-dropbox-integration')}
										disabled={isSaving}
									/>
								</div>

								<div className="edbi-form-group">
									<label htmlFor="edbi_client_secret">{__('App Secret', 'easy-dropbox-integration')}</label>
									<input
										type="text"
										id="edbi_client_secret"
										name="client_secret"
										className="edbi-form-input"
										value={formData.client_secret}
										onChange={handleChange}
										placeholder={__('Enter your Dropbox App Secret', 'easy-dropbox-integration')}
										disabled={isSaving}
									/>
								</div>

								<div className="edbi-form-group">
									<label htmlFor="edbi_redirect_uri">{__('Redirect URI', 'easy-dropbox-integration')}</label>
									<div className="edbi-input-with-copy">
										<input
											type="text"
											id="edbi_redirect_uri"
											className="edbi-form-input edbi-form-input--readonly"
											value={redirectUri}
											readOnly
										/>
										<button
											type="button"
											className="edbi-copy-button"
											onClick={() => handleCopy(redirectUri)}
										>
											<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
												<path d="M10.5 2H3.5C2.67 2 2 2.67 2 3.5V11.5H3.5V3.5C3.5 3.22 3.72 3 4 3H10.5V2ZM12.5 4H5.5C4.67 4 4 4.67 4 5.5V12.5C4 13.33 4.67 14 5.5 14H12.5C13.33 14 14 13.33 14 12.5V5.5C14 4.67 13.33 4 12.5 4ZM12.5 12.5H5.5V5.5H12.5V12.5Z" fill="currentColor"/>
											</svg>
											<span className="edbi-copy-text">{__('Copy', 'easy-dropbox-integration')}</span>
										</button>
									</div>
									<p className="edbi-form-help">{__('Use this as your Redirect URI in the Dropbox App Console.', 'easy-dropbox-integration')}</p>
								</div>

								<button type="submit" className="edbi-submit-button edbi-submit-button--primary" disabled={isSaving}>
									<span className="edbi-button-text">
										{isSaving ? __('Saving...', 'easy-dropbox-integration') : __('Save & Continue', 'easy-dropbox-integration')}
									</span>
									<span className="edbi-button-spinner" style={{ display: isSaving ? 'inline-block' : 'none' }}>
										<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
											<circle cx="8" cy="8" r="6" stroke="currentColor" strokeWidth="2" strokeDasharray="3 3" className="edbi-spinner"/>
										</svg>
									</span>
								</button>
							</form>
						</div>

						{/* Right Column: Video */}
						<div className="edbi-app-setup__video-section">
							<div className="edbi-video-wrapper">
								<iframe
									width="560"
									height="315"
									src="https://www.youtube.com/embed/AzLUtO0EWwI"
									title={__('How to Connect Dropbox App', 'easy-dropbox-integration')}
									allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
									allowFullScreen
								/>
							</div>
							<div className="edbi-video-info">
								<h3>{__('Step-by-Step Tutorial', 'easy-dropbox-integration')}</h3>
								<p>{__('Watch this quick video to learn how to create your Dropbox app and connect it to Easy Dropbox Integration.', 'easy-dropbox-integration')}</p>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	);
};

export default AppSetup;
