import { useEffect, useRef, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { Button } from '@wordpress/components';
import { desktop, tablet, mobile } from '@wordpress/icons';
import { usePreviewBridge } from '../hooks/usePreviewBridge';
import PreviewSkeleton from './PreviewSkeleton';

const DEVICES = [
	{ id: 'desktop', icon: desktop, label: __( 'Desktop', 'wuppi' ), width: null },
	{ id: 'tablet',  icon: tablet,  label: __( 'Tablet', 'wuppi' ),  width: 1024 },
	{ id: 'mobile',  icon: mobile,  label: __( 'Mobile', 'wuppi' ),  width: 390 },
];

export default function PreviewFrame( { settings, homeUrl, previewOrigin } ) {
	const iframeRef = useRef( null );
	const [ isReady, setReady ] = useState( false );
	const [ device, setDevice ] = useState( 'desktop' );

	useEffect( () => {
		const onMessage = ( event ) => {
			if ( event.origin !== previewOrigin ) {
				return;
			}
			if ( event?.data?.type === 'wuppi:ready' ) {
				setReady( true );
			}
		};
		window.addEventListener( 'message', onMessage );
		return () => window.removeEventListener( 'message', onMessage );
	}, [ previewOrigin ] );

	usePreviewBridge( { iframeRef, settings, previewOrigin, isReady, device } );

	return (
		<div className={ `wuppi-preview-pane wuppi-preview-pane--${ device }` }>
			<div className="wuppi-device-toolbar">
				<div className="wuppi-device-toolbar__devices">
					{ DEVICES.map( ( d ) => (
						<Button
							key={ d.id }
							icon={ d.icon }
							label={ d.label }
							isPressed={ device === d.id }
							onClick={ () => setDevice( d.id ) }
							showTooltip
							size="compact"
						/>
					) ) }
				</div>
			</div>
			<div className="wuppi-preview-viewport">
				{ ! isReady && <PreviewSkeleton /> }
				<iframe
					ref={ iframeRef }
					className="wuppi-preview-iframe"
					title={ __( 'Wuppi live preview', 'wuppi' ) }
					src={ homeUrl }
					style={ { opacity: isReady ? 1 : 0 } }
				/>
			</div>
		</div>
	);
}
