import { __ } from "@wordpress/i18n";
import { useBlockProps } from "@wordpress/block-editor";
import OptionsSelectControl from "./OptionsSelectControl";
import { useSelect } from "@wordpress/data";
import "./editor.scss";
import arrow from "./img/arrow-right-circle.svg";

export default function Edit({ attributes, setAttributes }) {
	const { relatedPostId, postType } = attributes;
	const page = useSelect((select) =>
		select("core").getEntityRecord("postType", postType, relatedPostId)
	);

	const pageIconUrl = useSelect(
		(select) => {
			if (postType === "page") {
				if (!page?.acf?.page_icon) return null;
				return select("core").getMedia(page?.acf?.page_icon)?.source_url;
			}
			if (postType === "parcours") {
				if (!page?.acf?.step_icon) return null;
				return select("core").getMedia(page?.acf?.step_icon)?.source_url;
			}
		},
		[page]
	);

	return (
		<>
			<OptionsSelectControl
				relatedPostId={relatedPostId}
				setAttributes={setAttributes}
				postType={postType}
			/>

			<div
				{...useBlockProps({
					className: `homegrade-blocks-page-card`,
				})}
			>
				{page && (
					<>
						<img
							className="homegrade-blocks-page-card__icon"
							src={pageIconUrl}
							alt=""
						/>

						<h3 className="homegrade-blocks-page-card__title">
							{page.title.rendered}
						</h3>
						<p className="homegrade-blocks-page-card__excerpt">
							{page.excerpt?.raw}
						</p>
						<div
							class="homegrade-blocks-page-card__cta"
							href="<?php echo $relatedPostUrl ?>"
							target="_self"
							rel="noopener"
						>
							<p>En savoir plus</p>
							<div class="cta_arrow_button">
								<img src={arrow} alt="" />
							</div>
						</div>
					</>
				)}
			</div>
		</>
	);
}
