import { __ } from '@wordpress/i18n';
import { InspectorControls } from '@wordpress/block-editor';
import { PanelBody, SelectControl, ComboboxControl } from '@wordpress/components';
import './editor.scss';
import { Tip } from '@wordpress/components';
import { getAdminLanguageFromCookie } from '../../utilities.js';
import { useSelect } from '@wordpress/data';
import { useEffect, useState } from '@wordpress/element';
import { decodeEntities } from '@wordpress/html-entities';

export default function OptionsSelectControl({ setAttributes, relatedPostId }) {
	let [postOptions, setPostOptions] = useState(null);

	const lang = getAdminLanguageFromCookie('wp-wpml_current_language');
	const optionPages = useSelect(
		(select) => {
			let query = {
				status: ['draft', 'publish'],
				per_page: -1,
				lang: lang,
			};
			return select('core').getEntityRecords('postType', 'parcours', query);
		},
		[lang]
	);
	const editUrl = relatedPostId
		? `${window.location.origin}/wp-admin/post.php?post=${relatedPostId}&action=edit`
		: null;

	function handleRelatedPostChange(postId) {
		setAttributes({ relatedPostId: Number(postId) });
	}

	function buildSelectOptions(optionPages) {
		let options = [];
		if (optionPages && optionPages.length > 0) {
			options.push({ value: 0, label: 'Selectionnez une page' });
			optionPages.forEach((page) => {
				options.push({
					value: page.id,
					label: decodeEntities(page.title.rendered),
				});
			});
		} else {
			options.push({ value: 0, label: 'Pas encore de questions...' });
		}
		return options;
	}

	useEffect(() => {
		if (!optionPages) return;
		if (optionPages && optionPages.length > 0) {
			setPostOptions(buildSelectOptions(optionPages));
		}
	}, [optionPages]);

	let panelTitle = 'Post Parcours Reliée';

	return (
		<InspectorControls>
			<PanelBody title={__('Étape parcours', 'homegrade-blocks')}>
				{postOptions && (
					<ComboboxControl
						label={panelTitle}
						value={relatedPostId}
						options={postOptions}
						onChange={(e) => handleRelatedPostChange(e)}
					/>
				)}
				{relatedPostId && (
					<Tip>
						{__(
							'Pour modifier le contenu de la question affichée ici, rendez-vous dans la fiche question correspondante.',
							'homegrade-blocks'
						)}
					</Tip>
				)}
				{relatedPostId && editUrl && (
					<a href={editUrl} className="edit-question-button">
						Éditer le post
					</a>
				)}
			</PanelBody>
		</InspectorControls>
	);
}
