import { __ } from "@wordpress/i18n";
import { useSelect } from "@wordpress/data";
import { useEntityRecord, useEntityProp } from "@wordpress/core-data";
import { useBlockProps, InspectorControls } from "@wordpress/block-editor";
import {
	FocalPointPicker,
	PanelBody,
	SelectControl,
	Button,
} from "@wordpress/components";
import "./editor.scss";

import FocusPointsControl from "./FocusPointControls";

// function getCurrentThematique(id) {
// 	const { record, isResolving } = useEntityRecord(
// 		"taxonomy",
// 		"thematiques",
// 		id
// 	);

// 	if (isResolving) {
// 		return "Loading...";
// 	}
// 	if (!record) {
// 		return "no post...";
// 	}
// 	return record;
// }

export default function Edit({ attributes, setAttributes }) {
	let { focusPoints } = attributes;
	// ### Load Taxonomies
	const currentTaxonomiesID = useSelect((select) =>
		select("core/editor").getCurrentPostAttribute("thematiques")
	);
	// ### Get current Thematique
	const mainTaxonomy = useSelect(
		(select) =>
			select("core").getEntityRecord(
				"taxonomy",
				"thematiques",
				currentTaxonomiesID[0] // or currentPost.thematiques[0] works as well
			),
		[currentTaxonomiesID]
	);
	const coverID =
		(mainTaxonomy && mainTaxonomy.acf.taxonomy_pictures.illustration_xl) ??
		null;

	const cover = useSelect(
		(select) => (coverID ? select("core").getMedia(coverID) : null),
		[coverID]
	);

	const coverUrl = cover && cover.source_url ? cover.source_url : null;

	return (
		<>
			<FocusPointsControl
				focusPoints={focusPoints}
				coverUrl={coverUrl}
				setAttributes={setAttributes}
			/>

			<section
				{...useBlockProps({
					className: `homegrade-blocks-illustration-thematique`,
				})}
			>
				{!cover && (
					<div>
						Pas d'images lié à cette thématique. Vérifiez que la thématique
						possède bien une image et qu'elle est bien une thématique parente.{" "}
					</div>
				)}
				{cover && cover.source_url && (
					<div>
						<img src={cover.source_url} alt="" />
					</div>
				)}
			</section>
		</>
	);
}
