import {PanelBody, PanelRow} from '@wordpress/components';
import {useEffect, useRef} from '@wordpress/element';
import {useBlockProps, InspectorControls} from '@wordpress/block-editor';
import Toggles from '../../../src/js/components/Settings/Toggles';
import {initToggle} from '../../../src/js/includes/functions';

export default function Edit({attributes, setAttributes}) {
	const {style = 1, data = {}} = attributes;
	const toggleRef = useRef(null);

	useEffect(() => {
		if (!toggleRef.current) return;

		const $ = window.jQuery;
		const $toggle = $(toggleRef.current);

		$toggle.data({
			style,
			data: data ? btoa(JSON.stringify(data)) : '',
			id: data?.id || '',
		});

		initToggle(toggleRef.current);

		return () => {
			$toggle.find('.dracula-toggle').remove();
		};

	}, [style, data]);


	return (
		<div {...useBlockProps()}>
			<InspectorControls>
				<PanelBody title="Switch Style" initialOpen>
					<PanelRow>
						<Toggles
							value={style}
							onChange={(style, newData) => {
								setAttributes({
									style: parseInt(style, 10),
									data: newData,
								});
							}}
						/>
					</PanelRow>
				</PanelBody>
			</InspectorControls>

			<div
				ref={toggleRef}
				className={`dracula-toggle-wrap ${data ? 'custom-toggle' : ''}`}
			/>
		</div>
	);
}
