import { useBlockProps } from "@wordpress/block-editor";
import { __ } from "@wordpress/i18n";
import "./editor.scss";
import SidePanel from "./side-panel";
import { useSelect } from "@wordpress/data";
import { store as coreDataStore } from "@wordpress/core-data";

export default function Edit({ attributes, setAttributes }) {
	const { searchBarId } = attributes;

	const blockProps = useBlockProps({
		className: "wp-block-orphic-ui-search-bar",
	});

	// Get selected search bar title
	const { searchBar } = useSelect(
		(select) => {
			const { getEntityRecord } = select(coreDataStore);
			return {
				searchBar: searchBarId
					? getEntityRecord("postType", "search_bar_orphic_ui", searchBarId)
					: null,
			};
		},
		[searchBarId],
	);

	return (
		<>
			<div {...blockProps}>
				<div className="search-bar-message">
					{searchBarId === 0 ? (
						__("Please select a search bar", "orphic-ui")
					) : (
						<>
							{__("You are using the search bar:", "orphic-ui")}{" "}
							<strong>{searchBar?.title?.rendered}</strong>
						</>
					)}
				</div>
			</div>
			<SidePanel attributes={attributes} setAttributes={setAttributes} />
		</>
	);
}
