import {
	ContrastChecker,
	InnerBlocks,
	InspectorControls,
	PanelColorSettings,
	useBlockProps,
} from "@wordpress/block-editor";
import {
	FormTokenField,
	PanelBody,
	QueryControls,
	SelectControl,
	ToggleControl,
} from "@wordpress/components";
import { useSelect } from "@wordpress/data";
import { RawHTML } from "@wordpress/element";
import { __ } from "@wordpress/i18n";
import "./editor.scss";

export default function Edit({ attributes, setAttributes }) {
	const {
		order,
		orderBy,
		numberOfItems,
		displayFeaturedImage,
		displayDescription,
		postType,
		categories,
		selectedTitles,
		textColor,
		backgroundColor,
		btnBackgroundColor,
		btnTextColor,
		selectedStyle,
	} = attributes;

	const postTypes = useSelect((select) => {
		return select("core").getPostTypes({ per_page: -1 });
	}, []);

	const catIds =
		categories && categories.length > 0 ? categories.map((cat) => cat.id) : [];
	const postTypeTaxonomy =
		postTypes && postTypes.length
			? postTypes.find((type) => type.slug === postType)?.taxonomies[0] ||
			"category"
			: "";
	const items = useSelect(
		(select) => {
			// If titles are selected, fetch posts by title
			if (selectedTitles && selectedTitles.length > 0) {
				const titleArgs = {
					per_page: -1, // Fetch all posts when selecting by title
					_embed: true,
				};

				return select("core").getEntityRecords("postType", postType, titleArgs);
			}

			// If no titles are selected, fall back to other queries (category, etc.)
			const otherQueryArgs = {
				per_page: numberOfItems,
				order,
				orderby: orderBy,
				_embed: true,
			};

			postType === "post"
				? (otherQueryArgs.categories = catIds)
				: (otherQueryArgs[postTypeTaxonomy] = catIds);

			return select("core").getEntityRecords(
				"postType",
				postType,
				otherQueryArgs,
			);
		},
		[
			postType,
			catIds,
			postTypeTaxonomy,
			numberOfItems,
			orderBy,
			order,
			selectedTitles,
		],
	);

	//For Post
	const allCats = useSelect(
		(select) => {
			return postTypeTaxonomy
				? select("core").getEntityRecords("taxonomy", postTypeTaxonomy, {
					per_page: -1,
				})
				: [];
		},
		[postTypeTaxonomy],
	);

	const catSuggestions = {};
	//For other post type
	if (allCats) {
		for (let i = 0; i < allCats.length; i++) {
			const cat = allCats[i];
			catSuggestions[cat.name] = cat;
		}
	}

	const onCategoryChange = (values) => {
		const hasNoSuggestions = values.some(
			(value) => typeof value === "string" && !catSuggestions[value],
		);
		if (hasNoSuggestions) return;

		const updatesCats = values.map((token) => {
			return typeof token === "string" ? catSuggestions[token] : token;
		});

		setAttributes({ categories: updatesCats });
	};
	const onChangeBackgroundColor = (newBgColor) => {
		setAttributes({ backgroundColor: newBgColor });
	};

	const onChangeTextColor = (newTextColor) => {
		setAttributes({ textColor: newTextColor });
	};

	const onChangebtnTextColor = (newTextColor) => {
		setAttributes({ btnTextColor: newTextColor });
	};

	const onChangeBtnBackgroundColor = (newBgColor) => {
		setAttributes({ btnBackgroundColor: newBgColor });
	};

	const onPostTypeChange = (value) => {
		setAttributes({ postType: value });
		setAttributes({ categories: [] });
	};

	const displayImageChange = (value) => {
		setAttributes({ displayFeaturedImage: value });
	};

	const displayDescriptionChange = (value) => {
		setAttributes({ displayDescription: value });
	};
	const onChangeStyle = (value) => {
		setAttributes({ selectedStyle: value });
	};
	const onSelectTitles = (selected) => {
		const titleObjs = selected.map((title) => {
			const foundPost = allPostTitles.find((post) => post.title === title);
			return foundPost ? foundPost : { id: null, title: title };
		});
		setAttributes({ selectedTitles: titleObjs });
	};

	const filteredItems = (items || []).filter(
		(item) =>
			!selectedTitles ||
			selectedTitles.length === 0 ||
			selectedTitles.some((titleObj) => titleObj.title === item.title.rendered),
	);

	const allPostTitles = useSelect(
		(select) => {
			const baseArgs = { per_page: -1 };

			if (catIds && catIds.length > 0) {
				baseArgs["categories"] = catIds;
			}

			const allPosts = select("core").getEntityRecords(
				"postType",
				postType,
				baseArgs,
			);
			return allPosts
				? allPosts.map((post) => ({ id: post.id, title: post.title.rendered }))
				: [];
		},
		[catIds],
	);

	const excludedSlugs = [
		"attachment",
		"nav_menu_item",
		"page",
		"team",
		"product",
		"event",
		"wp_block",
		"wp_template",
		"wp_template_part",
		"wp_navigation",
		"wp_font_face",
		"wp_font_family"
		];
		
	//sort post by selected title wise
	function sortPostsBySelectedTitles(posts, selectedTitles) {
		const sortedPosts = [];

		// Iterate through the selectedTitles and find matching posts
		selectedTitles.forEach((titleObj) => {
			const matchingPost = posts.find(
				(post) => titleObj.title === post.title.rendered,
			);
			if (matchingPost) {
				sortedPosts.push(matchingPost);
			}
		});

		// Add remaining posts that were not in selectedTitles
		posts.forEach((post) => {
			if (
				!selectedTitles.some(
					(titleObj) => titleObj.title === post.title.rendered,
				)
			) {
				sortedPosts.push(post);
			}
		});

		return sortedPosts;
	}
	const sortedItems = sortPostsBySelectedTitles(filteredItems, selectedTitles);
	return (
		<div>
			<InspectorControls>
				<PanelBody>
					<SelectControl
						label={__("Select Post Type", "artcloud-blocks")}
						value={postType}
						options={
							postTypes
								? postTypes
									.filter((type) => !excludedSlugs.includes(type.slug))
									.map((type) => ({
										label: type.name,
										value: type.slug,
									}))
								: []
						}
						onChange={onPostTypeChange}
					/>
					<SelectControl
						label={__("Select Style", "artcloud-blocks")}
						value={selectedStyle}
						options={[
							{ label: __("Style 1", "artcloud-blocks"), value: "style1" },
							{ label: __("Style 2", "artcloud-blocks"), value: "style2" },
							// Add more styles as needed
						]}
						onChange={onChangeStyle}
					/>
					<ToggleControl
						label={__("Display Content", "artcloud-blocks")}
						checked={displayDescription}
						onChange={displayDescriptionChange}
					/>
					<QueryControls
						categorySuggestions={catSuggestions}
						selectedCategories={categories}
						onCategoryChange={onCategoryChange}
						order={order}
						onOrderChange={(value) => setAttributes({ order: value })}
						orderBy={orderBy}
						onOrderByChange={(value) => setAttributes({ orderBy: value })}
					/>
					<FormTokenField
						label="Select Posts by Title"
						value={selectedTitles.map((titleObj) => titleObj.title)}
						suggestions={allPostTitles.map((post) => post.title)}
						onChange={onSelectTitles}
					/>
				</PanelBody>
				<PanelColorSettings
					title={__("Color Settings", "artcloud-blocks")}
					icon="admin-appearance"
					initialOpen="false"
					colorSettings={[
						{
							value: backgroundColor,
							onChange: onChangeBackgroundColor,
							label: __("Background Color", "artcloud-blocks"),
						},
						{
							value: textColor,
							onChange: onChangeTextColor,
							label: __("Text Color", "artcloud-blocks"),
						},
						{
							value: btnBackgroundColor,
							onChange: onChangeBtnBackgroundColor,
							label: __("Button BG Color", "artcloud-blocks"),
						},
						{
							value: btnTextColor,
							onChange: onChangebtnTextColor,
							label: __("ButtonText Color", "artcloud-blocks"),
						},
					]}
				>
					<ContrastChecker
						textColor={textColor}
						backgroundColor={backgroundColor}
					/>
				</PanelColorSettings>
			</InspectorControls>
			<div {...useBlockProps()}>
				{sortedItems &&
					sortedItems.map((post) => {
						const postImage =
							post._embedded &&
							post._embedded["wp:featuredmedia"] &&
							post._embedded["wp:featuredmedia"].length > 0 &&
							post._embedded["wp:featuredmedia"][0];
						const postContent = post.excerpt.rendered;
						const defaultImage = window.location.origin + '/wp-content/plugins/artcloud-blocks/assets/img/default-image.jpg'
						return (
							<div
								className={`image-cards ${selectedStyle === "style1" ? "" : "row-reverse"
									}`}
							>
								<div
									className="post-image"
									style={{
										position: "relative",
										padding: "5rem 0rem 5rem 0rem",
									}}
								>
									{displayFeaturedImage && (
										<img alt={postImage && postImage.alt_text}
											src={postImage && postImage.media_details.sizes.full.source_url ? postImage.media_details.sizes.full.source_url : defaultImage} />
									)}
								</div>
								<div
									className="post-content"
									style={{ backgroundColor: backgroundColor }}
								>
									<InnerBlocks
										template={[
											['artcloud-blocks/artcloud-icon', { className: 'artcloud-icon', textAlign: 'left' }],
										]}
										templateLock="all"
									/>
									<h2 style={{ color: textColor }}>{post.title.rendered}</h2>
									<RawHTML>
										{displayDescription && postContent && postContent}
									</RawHTML>
									<a
										style={{
											backgroundColor: btnBackgroundColor,
											color: btnTextColor,
										}}
										className="wp-block-button__link wp-element-button-readmore"
										href={post.link}
									>
										{__("Lue lisää", "artcloud-blocks")}
									</a>
								</div>
							</div>
						);
					})}
			</div>
		</div>
	);
}
