import { InspectorControls } from "@wordpress/block-editor";
import {
	PanelBody,
	SelectControl,
	Button,
	Spinner,
	Notice,
} from "@wordpress/components";
import { useState, useEffect } from "@wordpress/element";
import { __ } from "@wordpress/i18n";
import { useSelect } from "@wordpress/data";
import { store as coreDataStore } from "@wordpress/core-data";

const SidePanel = ({ attributes, setAttributes }) => {
	const { searchBarId } = attributes;
	const [isCreating, setIsCreating] = useState(false);

	// Fetch all search bar posts
	const { searchBars, isLoading } = useSelect((select) => {
		const { getEntityRecords } = select(coreDataStore);

		const query = {
			status: "publish",
			per_page: -1,
		};

		return {
			searchBars:
				getEntityRecords("postType", "search_bar_orphic_ui", query) || [],
			isLoading: !select(coreDataStore).hasFinishedResolution(
				"getEntityRecords",
				["postType", "search_bar_orphic_ui", query],
			),
		};
	}, []);

	// Create options for select control
	const searchBarOptions = [
		{ label: __("Select a Search Bar", "orphic-ui"), value: 0 },
		...(searchBars || []).map((post) => ({
			label: post.title.rendered,
			value: post.id,
		})),
	];

	// Handle creating new search bar
	const handleCreateNew = () => {
		setIsCreating(true);
		window.location.href =
			"/wp-admin/post-new.php?post_type=search_bar_orphic_ui";
	};

	// Get selected search bar title
	const selectedSearchBar = searchBars?.find((post) => post.id === searchBarId);

	return (
		<InspectorControls>
			<PanelBody title={__("Search Bar Settings", "orphic-ui")}>
				{isLoading ? (
					<Spinner />
				) : searchBars?.length === 0 ? (
					<Notice status="info" isDismissible={false}>
						{__("No search bars found. Create your first one!", "orphic-ui")}
					</Notice>
				) : (
					<>
						<SelectControl
							label={__("Select Search Bar", "orphic-ui")}
							value={searchBarId}
							options={searchBarOptions}
							onChange={(value) =>
								setAttributes({ searchBarId: parseInt(value) })
							}
						/>
						{searchBarId > 0 && (
							<Notice status="info" isDismissible={false}>
								{__("Your search bar: ", "orphic-ui")}
								<strong>{selectedSearchBar?.title.rendered}</strong>
							</Notice>
						)}
					</>
				)}

				<div style={{ marginTop: "10px" }}>
					<Button
						variant="secondary"
						onClick={handleCreateNew}
						disabled={isCreating}
						isFullWidth
					>
						{isCreating
							? __("Redirecting...", "orphic-ui")
							: __("Create New Search Bar", "orphic-ui")}
					</Button>
				</div>
			</PanelBody>
		</InspectorControls>
	);
};

export default SidePanel;
