/* global WebEngineDEFAULTS */

import { __ } from '@wordpress/i18n';
import { useEntityProp } from '@wordpress/core-data';
import { useSelect } from '@wordpress/data';
import React from 'react';
import { BaseControl, Dashicon, Card, CardBody } from '@wordpress/components';

// import SidebarCollapsible from './SidebarCollapsible';
import WEVCPlayback from './WEVCPlayback';
import WEVCConfigure from './WEVCConfigure';

// export default WEVCPanel = () => {
//export default function WEVCPanel( { settings } ) {
export default function WEVCPanel() {
	// useEffect(async()=>{
	// 	// probalby simpler to embed this project into the compoennt!
	// 	window.WebEngineVideoCallout && window.WebEngineVideoCallout.GetAdminPreview();

	//   },[]);

	const postType = useSelect(
		(select) => select('core/editor').getCurrentPostType(),
		[]
	);

	// Get the value of meta and a function for updating meta from useEntityProp.
	const [meta, setMeta] = useEntityProp('postType', postType, 'meta');

	// Define which post meta key to read from/save to.
	const metaVideoId = 'wevideopopup_video_id';

	const metaAutoplay = 'wevideopopup_autoplay';
	const metaMute = 'wevideopopup_mute';
	const metaClass = 'wevideopopupClass';
	const metaAdvancedPosition = 'pin';

	const defaults = window.WebEngineDEFAULTS;

	const metaAdvanced = 'wevideopopup_advanced';
	// YUK! - functional component would alow us to squirrel this away better
	const getAdvanced = (key) => {
		try {
			const result = JSON.parse(meta[metaAdvanced]);
			return result[key] || '';
		} catch {
			return '';
		}
	};
	// used in translations
	/**
	 * A helper function for getting post meta by key.
	 *
	 * @param {string} key - The meta key to read.
	 * @return {*} - Meta value.
	 */
	const getPostMeta = (key) => meta[key] || '';

	/**
	 * A helper function for updating post meta that accepts a meta key and meta
	 * value rather than entirely new meta object.
	 *
	 * Important! Don't forget to register_post_meta (see ../index.php).
	 *
	 * @param {string} key   - The meta key to update.
	 * @param {*}      value - The meta value to update.
	 */
	const setPostMeta = (key, value) =>
		setMeta({
			...meta,
			[key]: value,
		});

	const showPreview = function () {
		if (window.WebEngineVideoCallout) {
			let width = parseInt(getAdvanced('width'));
			if (!width > 0) {
				width = window.WebEngineDEFAULTS.styles.frame.width;
			}
			let height = parseInt(getAdvanced('height'));
			if (!height > 0) {
				height = window.WebEngineDEFAULTS.styles.frame.height;
			}
			// Start time
			let videoid = getPostMeta(metaVideoId);
			if (getVideoInfo(videoid).type === 'vimeo') {
				videoid = videoid.replace('#', '&');
			}
			const urlParams = new URLSearchParams(videoid);
			//console.info('preview', width, height);
			// TODO - get these values - either from options
			// or compute from the form
			const payload = defaults;
			// ::TODO:: parse the video id??
			payload.autoplay = getPostMeta(metaAutoplay) !== '';
			if (payload.autoplay) {
				payload.autoplay = isTrue(getPostMeta(metaAutoplay));
			} else {
				payload.autoplay = WebEngineDEFAULTS.globalSettings.mute;
			}
			if (getPostMeta(metaMute) !== '') {
				payload.mute = isTrue(getPostMeta(metaMute)) ? true : false;
			} else {
				payload.mute = WebEngineDEFAULTS.globalSettings.mute;
			}
			payload.frequencyPeriod = 0;
			payload.frequencyRange = 0;
			payload.frequency = 0;
			payload.delay = 0;
			payload.starttime = urlParams.get('t') ? urlParams.get('t') : 0;
			payload.extraClasses =
				getPostMeta(metaClass) !== ''
					? getPostMeta(metaClass)
					: WebEngineDEFAULTS.styles.window.class;
			payload.styles.window.position =
				getAdvanced(metaAdvancedPosition) !== ''
					? getAdvanced(metaAdvancedPosition)
					: WebEngineDEFAULTS.styles.window.position;
			if (width > 0) {
				payload.styles.frame.width = width;
			}
			if (height > 0) {
				payload.styles.frame.height = height;
			}
			const videoInfo = getVideoInfo(getPostMeta(metaVideoId));
			if (videoInfo) {
				payload.type = videoInfo.type;
				payload.id = videoInfo.id;
			}
			window.WebEngineVideoCallout.GetAdminPreview(payload);
		}
	};

	//
	// const handleFrequencyChange = (e)

	const getVideoInfo = (url) => {
		let test;
		if (
			(test =
				/\byoutu(\.be|be\.com)\b.*(\/|\?v=)(?<id>[a-zA-Z0-9\-_]{11})/.exec(
					url
				))
		) {
			return {
				id: test.groups.id,
				type: 'youtube',
			};
		} else if (
			(test =
				/\bdrive\.google\.com\b.*(\/)(?<id>[a-zA-Z0-9\-_]{33})(\/)/.exec(
					url
				))
		) {
			return {
				id: test.groups.id,
				type: 'googleDrive',
			};
		} else if (
			(test = /\bvimeo\.com\b.*\/(?<id>[0-9]+)([^0-9].*)?$/.exec(url))
		) {
			return {
				id: test.groups.id,
				type: 'vimeo',
			};
		}
		return null;
	};
	const isTrue = (val) => {
		return val === '1' || val === true || val === 'true';
	};
	return (
		<>
			<Card>
				<CardBody>
					<div className="we-vc-meta_header">
						<p>
							{__(
								'Defaults and general styling can be configured from the',
								'video-callout'
							)}{' '}
							<a
								href={
									defaults.settings_url
										? defaults.settings_url
										: ''
								}
							>
								{__('settings page', 'video-callout')}
							</a>
							.
						</p>
						{/* <img src="image/vp-icon-colour.svg" width="70" alt="" /> */}
					</div>
					<BaseControl
						id="wevideopopup_video_id"
						label={__('Video address', 'video-callout')}
						help={__(
							'YouTube, Google Drive, or Vimeo URL.',
							'video-callout'
						)}
					>
						<div className="wevideopopup_video_idInput">
							<input
								id="wevideopopup_video_id"
								name="wevideopopup_video_id"
								type="url"
								onChange={(e) =>
									setPostMeta(metaVideoId, e.target.value)
								}
								value={getPostMeta(metaVideoId)}
							/>
							<button
								disabled={!getPostMeta(metaVideoId)}
								title="Clear"
								onClick={() => setPostMeta(metaVideoId, '')}
							>
								<span className="dashicons dashicons-trash"></span>
							</button>
						</div>
					</BaseControl>
				</CardBody>
			</Card>
			{getPostMeta(metaVideoId) !== '' && (
				<>
					<WEVCPlayback
						default_autoplay={
							WebEngineDEFAULTS.globalSettings.autoplay
						}
						default_delay={WebEngineDEFAULTS.globalSettings.delay}
						defaultFrequencyPeriod={
							WebEngineDEFAULTS.globalSettings.frequencyPeriod
						}
						defaultFrequencyRange={
							WebEngineDEFAULTS.globalSettings.frequencyRange
						}
						default_mute={WebEngineDEFAULTS.globalSettings.mute}
						default_launchclass=""
						default_popup="1"
						default_controls="1"
					/>

					<WEVCConfigure
						defaultWidth={WebEngineDEFAULTS.styles.frame.width}
						defaultHeight={WebEngineDEFAULTS.styles.frame.height}
						defaultPosition={
							WebEngineDEFAULTS.styles.window.position
						}
						defaultClass={WebEngineDEFAULTS.styles.window.class}
					/>
					<button
						className="we-vp-preview-panel-button"
						data-wevc-preview
						onClick={showPreview}
						onKeyUp={(e) => {
							if (e.key === 'Enter' || e.key === ' ') {
								showPreview();
							}
						}}
					>
						<Dashicon icon="format-video" />{' '}
						{__('Preview', 'video-callout')}
					</button>
				</>
			)}
		</>
	);
}
