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 { useSelect } from "@wordpress/data";
import { useEffect, useState } from "@wordpress/element";
import { decodeEntities } from "@wordpress/html-entities";

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

	const editUrl = relatedPostId
		? `${window.location.origin}/wp-admin/post.php?post=${relatedPostId}&action=edit`
		: null;

	function handleRelatedPostChange(postId) {
		setAttributes({ relatedPostId: Number(postId) });
	}
	function buildSelectOptions(relatedPossiblePages) {
		let options = [];
		if (relatedPossiblePages) {
			options.push({ value: 0, label: "Selectionnez une page" });
			relatedPossiblePages.forEach((page) => {
				options.push({
					value: page.id,
					label: decodeEntities(page.title.rendered),
				});
			});
		} else {
			options.push({ value: 0, label: "Pas encore de questions..." });
		}
		return options;
	}

	const relatedPossiblePages = useSelect((select) => {
		let query = {
			status: "publish",
			per_page: -1,
		};
		return select("core").getEntityRecords("postType", "articles", query);

		return null;
	});

	useEffect(() => {
		if (relatedPossiblePages) {
			setRelatedArticlePages(buildSelectOptions(relatedPossiblePages));
		}
	}, [relatedPossiblePages]);

	let panelTitle = "";
	return (
		<InspectorControls>
			<PanelBody title={__("Article lié", "dynamiques-blocks")}>
				{relatedArticlePages && (
					<ComboboxControl
						label={panelTitle}
						value={relatedPostId}
						options={relatedArticlePages}
						onChange={(e) => handleRelatedPostChange(e)}
					/>
				)}

				{relatedPostId && (
					<Tip>
						{__(
							"Pour modifier le contenu de l'article affiché ici, rendez-vous dans l'article correspondant",
							"homegrade-blocks",
						)}
					</Tip>
				)}
				{relatedPostId && editUrl && (
					<a href={editUrl} className="edit-question-button">
						Editer l'article
					</a>
				)}
			</PanelBody>
		</InspectorControls>
	);
}
