/**
 * Auth Frame Component.
 *
 * Displays Sideconvo platform in an iframe for authentication.
 *
 * @package Sideconvo
 */

import { useState, useEffect } from '@wordpress/element';
import { useAuth } from '../../contexts/AuthContext';
import { useSettings } from '../../contexts/SettingsContext';
import './auth-frame.css';

interface AuthFrameProps {
	onClose: () => void;
}

/**
 * Auth Frame component.
 *
 * @param {AuthFrameProps} props Component props.
 * @return {JSX.Element} Auth frame component.
 */
export default function AuthFrame({ onClose }: AuthFrameProps) {
	const { saveApiKey } = useAuth();
	const { showNotification } = useSettings();
	const [isLoading, setIsLoading] = useState(false);
	const [iframeUrl, setIframeUrl] = useState('');
	const [isFetchingUrl, setIsFetchingUrl] = useState(true);
	const [fetchError, setFetchError] = useState(false);

	useEffect(() => {
		const platformUrl = (window as any).sideconvoData?.platformUrl;

		// Fetch site info and build iframe URL
		const fetchSiteInfo = async () => {
			setIsFetchingUrl(true);
			setFetchError(false);

			try {
				const response = await fetch(
					`${(window as any).sideconvoData.restUrl}sideconvo/v1/site-info`,
					{
						headers: {
							'X-WP-Nonce': (window as any).sideconvoData.nonce,
						},
					}
				);

				if (!response.ok) {
					throw new Error('Failed to fetch site info');
				}

				const siteInfo = await response.json();

				if (platformUrl && siteInfo.domain) {
					// Build iframe URL with add-site route
					const url = `${platformUrl}#/add-site?site_url=${encodeURIComponent(siteInfo.domain)}&is_iframe=true`;
					setIframeUrl(url);
					setIsFetchingUrl(false);
				} else {
					throw new Error('Missing platform URL or site domain');
				}
			} catch (error) {
				console.error('Error fetching site info:', error);
				setFetchError(true);
				setIsFetchingUrl(false);
			}
		};

		fetchSiteInfo();

		// Listen for postMessage from iframe
		const handleMessage = async (event: MessageEvent) => {
			// Verify origin matches platform URL
			if (!platformUrl || !event.origin.includes('sideconvo.ai')) {
				return;
			}

			// Check if message contains a payment redirect URL (Stripe blocks iframes)
			if (event.data && event.data.type === 'sideconvo-payment') {
				const paymentUrl = event.data.url;
				if (paymentUrl) {
					window.open(paymentUrl, '_blank', 'noopener,noreferrer');
				}
				return;
			}

			// Check if message contains API key
			if (event.data && event.data.type === 'sideconvo-auth') {
				const apiKey = event.data.apiKey;

				if (apiKey) {
					setIsLoading(true);

					try {
						const success = await saveApiKey(apiKey);

						if (success) {
							showNotification(
								'success',
								'Successfully connected to Sideconvo!'
							);
							// App will auto-refresh due to auth state change
						} else {
							showNotification(
								'error',
								'Failed to validate API key. Please try again.'
							);
							setIsLoading(false);
						}
					} catch (error) {
						showNotification(
							'error',
							'An error occurred while connecting. Please try again.'
						);
						setIsLoading(false);
					}
				}
			}
		};

		window.addEventListener('message', handleMessage);

		// Also check URL parameters (for redirect from platform)
		const urlParams = new URLSearchParams(window.location.search);
		const apiKeyFromUrl = urlParams.get('api_key');

		if (apiKeyFromUrl) {
			(async () => {
				setIsLoading(true);
				try {
					const success = await saveApiKey(apiKeyFromUrl);

					if (success) {
						showNotification(
							'success',
							'Successfully connected to Sideconvo!'
						);
						// Clean URL
						window.history.replaceState(
							{},
							'',
							window.location.pathname
						);
					} else {
						showNotification(
							'error',
							'Failed to validate API key. Please try again.'
						);
						setIsLoading(false);
					}
				} catch (error) {
					showNotification(
						'error',
						'An error occurred while connecting. Please try again.'
					);
					setIsLoading(false);
				}
			})();
		}

		return () => {
			window.removeEventListener('message', handleMessage);
		};
	}, [saveApiKey, showNotification]);

	const handleClose = () => {
		if (!isLoading) {
			onClose();
		}
	};

	return (
		<div className="sideconvo-auth-frame">
			<div className="sideconvo-auth-frame__header">
				<h2>Connect to Sideconvo</h2>
				<button
					className="sideconvo-auth-frame__close"
					onClick={handleClose}
					disabled={isLoading}
					aria-label="Close"
				>
					<svg
						width="24"
						height="24"
						viewBox="0 0 24 24"
						fill="none"
						xmlns="http://www.w3.org/2000/svg"
					>
						<path
							d="M18 6L6 18M6 6L18 18"
							stroke="currentColor"
							strokeWidth="2"
							strokeLinecap="round"
							strokeLinejoin="round"
						/>
					</svg>
				</button>
			</div>

			<div className="sideconvo-auth-frame__content">
				{isLoading ? (
					<div className="sideconvo-auth-frame__loading">
						<div className="sideconvo-auth-frame__spinner" />
						<p>Validating your connection...</p>
					</div>
				) : isFetchingUrl ? (
					<div className="sideconvo-auth-frame__loading">
						<div className="sideconvo-auth-frame__spinner" />
						<p>Loading authentication page...</p>
					</div>
				) : fetchError ? (
					<div className="sideconvo-auth-frame__error">
						<p>Failed to load authentication page.</p>
						<button
							onClick={handleClose}
							className="sideconvo-button sideconvo-button--secondary"
						>
							Close
						</button>
					</div>
				) : (
					<iframe
						src={iframeUrl}
						className="sideconvo-auth-frame__iframe"
						title="Sideconvo Authentication"
						allow="clipboard-read; clipboard-write; payment"
					/>
				)}
			</div>
		</div>
	);
}
