import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
import {
	PanelBody,
	TextControl,
	SelectControl,
	CheckboxControl,
} from '@wordpress/components';
import {
	useEffect,
	useState,
	createInterpolateElement,
} from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { tool } from '@wordpress/icons';
import apiFetch from '@wordpress/api-fetch';

export default function Edit(props) {
	const blockProps = useBlockProps();
	const { attributes, setAttributes } = props;
	const [previewBlockContent, setPreviewBlockContent] = useState('');

	// view options available
	const viewOptions = [
		{ label: __('Tabellarisch', 'ticketleo-events'), value: 'table' },
		{ label: __('Liste', 'ticketleo-events'), value: 'list' },
		{ label: __('Kacheln', 'ticketleo-events'), value: 'grid' },
	];

	// Don't set attributes for grid view
	useEffect(() => {
		if (attributes.viewOptionValue === 'grid') {
			if (
				attributes.showMetaDataLabel !== undefined ||
				attributes.showMetaDataStatus !== undefined
			) {
				setAttributes({
					showMetaDataLabel: undefined,
					showMetaDataStatus: undefined,
				});
			}
		} else {
			const updates = {};
			if (attributes.showMetaDataLabel === undefined) {
				updates.showMetaDataLabel = false;
			}
			if (attributes.showMetaDataStatus === undefined) {
				updates.showMetaDataStatus = false;
			}

			if (Object.keys(updates).length > 0) {
				setAttributes(updates);
			}
		}
	}, [
		attributes.viewOptionValue,
		attributes.showMetaDataLabel,
		attributes.showMetaDataStatus,
	]);

	// Get block content and show render_callback content inside block editor
	useEffect(() => {
		apiFetch({
			path: `/wp/v2/block-renderer/${props.name}`,
			method: 'POST',
			data: {
				context: 'edit',
				attributes: attributes,
			},
		})
			.then((response) => {
				setPreviewBlockContent(response.rendered);
			})
			.catch((error) => {
				console.error('Error fetching block content:', error);
				setPreviewBlockContent('');
			});
	}, [attributes, props.name]);

	// Set Event-ID
	function setEventID(value) {
		const newValue = value === '' ? undefined : Number(value);
		setAttributes({ eventId: newValue });
	}

	// Set view option for frontend styling
	function setViewOption(newView) {
		setAttributes({ viewOptionValue: newView });
	}

	// Set metadata, that's supposed to render in frontend
	function toggleMetaData(option) {
		if (option === 'label') {
			setAttributes({ showMetaDataLabel: !attributes.showMetaDataLabel });
		}
		if (option === 'status') {
			setAttributes({ showMetaDataStatus: !attributes.showMetaDataStatus });
		}
	}

	function toggleReservationInterface() {
		setAttributes({
			showReservationInterface: !attributes.showReservationInterface,
		});
	}

	const shouldShowMetaDataControls = attributes.viewOptionValue !== 'grid';

	return (
		<>
			<InspectorControls>
				<PanelBody
					title={__('Einstellungen', 'ticketleo-events')}
					initialOpen={true}
					icon={tool}
				>
					<TextControl
						label={__('Event-ID', 'ticketleo-events')}
						value={attributes.eventId}
						onChange={setEventID}
						type='number'
						__nextHasNoMarginBottom={true}
						__next40pxDefaultSize={true}
						help={createInterpolateElement(
							__(
								'Wie Sie diese herausfinden, können Sie <a>hier</a> sehen.',
								'ticketleo-events'
							),
							{
								a: (
									<a
										href={`${window.location.origin}/wp-content/plugins/ticketleo-events/docs/find-ids.pdf`}
										target='_blank'
										rel='noopener noreferrer'
									/>
								),
							}
						)}
					/>

					<div style={{ marginTop: '10px', marginBottom: '20px' }}>
						<CheckboxControl
							label={__(
								'Reservierungsoberfläche integrieren',
								'ticketleo-events'
							)}
							checked={!!attributes.showReservationInterface}
							onChange={toggleReservationInterface}
							__nextHasNoMarginBottom={true}
							help={createInterpolateElement(
								__(
									'Wie Sie diese integrieren, finden Sie <a>hier</a>.',
									'ticketleo-events'
								),
								{
									a: (
										<a
											href={`${window.location.origin}/wp-content/plugins/ticketleo-events/docs/integrate-reservation.pdf`}
											target='_blank'
											rel='noopener noreferrer'
										/>
									),
								}
							)}
						/>
					</div>
					{!attributes.showReservationInterface && (
						<>
							<SelectControl
								label={__('Ansicht', 'ticketleo-events')}
								value={attributes.viewOptionValue}
								options={viewOptions}
								onChange={setViewOption}
								__nextHasNoMarginBottom={true}
								__next40pxDefaultSize={true}
							/>

							{shouldShowMetaDataControls && (
								<div style={{ marginBlock: '20px' }}>
									<label>
										{__('Metadaten einblenden', 'ticketleo-events')}
									</label>
									<div style={{ marginTop: '10px' }}>
										<CheckboxControl
											label={__('Bezeichnung', 'ticketleo-events')}
											checked={!!attributes.showMetaDataLabel}
											onChange={() => toggleMetaData('label')}
											__nextHasNoMarginBottom={true}
										/>
										<CheckboxControl
											label={__('Status', 'ticketleo-events')}
											checked={!!attributes.showMetaDataStatus}
											onChange={() => toggleMetaData('status')}
											__nextHasNoMarginBottom={true}
										/>
									</div>
								</div>
							)}
						</>
					)}
				</PanelBody>
			</InspectorControls>
			<div {...blockProps}>
				<div dangerouslySetInnerHTML={{ __html: previewBlockContent }} />
			</div>
		</>
	);
}
