import { useEffect } from 'react';
import {
	DyteProvider,
	useDyteClient,
	useDyteMeeting,
	useDyteSelector,
} from '@dytesdk/react-web-core';
import { DytePluginMain, DytePlugins } from '@dytesdk/react-ui-kit';

function PluginApp() {
	const [meeting, initMeeting] = useDyteClient();
	const url = new URL(window.location.href);
	const queryToken = url.searchParams.get('authToken');

	if (!queryToken) {
		alert('Please add authToken to url query params');
	}

	useEffect(() => {
		const init = async () => {
			if (!queryToken) return;

			await initMeeting({
				authToken: queryToken,
				defaults: {
					video: false,
					audio: false,
				},
			}).then(async (meet) => {
				if (!meet) return;

				await meet.join();
			});
		};
		init();
	}, []);

	if (!meeting) {
		return <div>Loading...</div>;
	}

	return (
		<DyteProvider value={meeting}>
			<PluginMeeting></PluginMeeting>
		</DyteProvider>
	);
}

export default PluginApp;

function PluginMeeting() {
	const { meeting } = useDyteMeeting();
	const activePlugin = useDyteSelector((state) => state.plugins.active.toArray()[0]);

	return (
		<div style={{ display: 'flex' }}>
			<div style={{ height: '100vh', width: '70%' }}>
				{activePlugin && <DytePluginMain meeting={meeting} plugin={activePlugin} />}
			</div>
			<div style={{ height: '100vh', width: '30%' }}>
				<DytePlugins meeting={meeting} />
			</div>
		</div>
	);
}
