import { ContrastChecker, InspectorControls, PanelColorSettings, RichText, 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 {
		numberOfItems,
		title,
		displayAuthorImage,
		displayDescription,
		displayDateAuthor,
		postType,
		categories,
		selectedAuthors,
		textColor,
		backgroundColor,
		btnBackgroundColor,
		btnTextColor
	} = attributes;

	const postTypes = useSelect((select) => {
		return select('core').getPostTypes();
	}, []);

	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 authorIds = selectedAuthors.map((author) => author.id).filter(Boolean);
	const items = useSelect(
		(select) => {
			const itemArgs = {
				per_page: numberOfItems,
				_embed: true,
			};

			// Set categories based on postType
			postType === 'post' ? (itemArgs.categories = catIds) : (itemArgs[postTypeTaxonomy] = catIds);

			// Map author names to IDs
			const authorIds = selectedAuthors.map((author) => author.id).filter(Boolean);

			// Set author directly in itemArgs
			if (authorIds.length > 0) {
				itemArgs.author = authorIds;
			}

			return select('core').getEntityRecords('postType', postType, itemArgs);
		},
		[postType, catIds, postTypeTaxonomy, numberOfItems, selectedAuthors]
	);


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

	const catSuggestions = {};
	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 allAuthors = wp.data.select('core').getEntityRecords('root', 'user');

	// Your onSelectAuthors function
	const onSelectAuthors = (selected) => {
		const authorObjs = selected.map((author) => {
			const foundAuthor = allAuthors.find((a) => a.name === author);
			return foundAuthor ? foundAuthor : { id: null, name: author };
		});
		setAttributes({ selectedAuthors: authorObjs });
	};
	const onChangeBackgroundColor = (newBgColor) => {
		setAttributes({ backgroundColor: newBgColor });
	};
	const onChangeTitle = (value) => {
		setAttributes({ title: value });
	};
	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({ displayAuthorImage: value });
	};

	const displayDateAuthorChange = (value) => {
		setAttributes({ displayDateAuthor: value });
	};

	const displayDescriptionChange = (value) => {
		setAttributes({ displayDescription: value });
	};

	const onNumberOfItemsChange = (value) => {
		setAttributes({ numberOfItems: value });
	};

	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"
		];

	const sortedItems = (items || []).sort((a, b) => a.title.rendered.localeCompare(b.title.rendered));

	return (
		<div {...useBlockProps()}>
			<InspectorControls>
				<PanelBody>
					<ToggleControl
						label={__('Display Image', 'artcloud-blocks')}
						checked={displayAuthorImage}
						onChange={displayImageChange}
					/>
					<ToggleControl
						label={__('Display Content', 'artcloud-blocks')}
						checked={displayDescription}
						onChange={displayDescriptionChange}
					/>
					<ToggleControl
						label={__('Display Date & Author', 'artcloud-blocks')}
						checked={displayDateAuthor}
						onChange={displayDateAuthorChange}
					/>
					<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}
					/>
					<QueryControls
						categorySuggestions={catSuggestions}
						selectedCategories={categories}
						onCategoryChange={onCategoryChange}
						numberOfItems={numberOfItems}
						onNumberOfItemsChange={onNumberOfItemsChange}
					/>
					<FormTokenField
						label={__('Select authors', 'artcloud-blocks')}
						value={selectedAuthors.map((authorObj) => authorObj.name)}
						suggestions={(allAuthors || []).map((author) => author.name)}
						onChange={onSelectAuthors}
					/>
				</PanelBody>
				<PanelColorSettings
					title={__('Color Settings', 'artcloud-blocks')}
					icon="admin-appearance"
					initialOpen
					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()}>
			<RichText
			tagName="h1"
			style={{ color: btnBackgroundColor }}
			className="post-block-title"
			placeholder={__('Enter title', 'artcloud-blocks')}
			value={title}
			onChange={onChangeTitle}
			allowedFormats={[]}
		/>
				<div className="row">
					{sortedItems.length > 0 ? (
						sortedItems.map((post) => {
							const authorName = post?._embedded?.author?.[0]?.name ?? '';
							const authorImage = post?._embedded?.author?.[0]?.avatar_urls['96'] ?? '';
							const postContent = post.excerpt.rendered;
							const postExcerpt = postContent.split(' ').slice(0, 8).join(' ');
							const postDate = new Date(post.date);

							const options = {
								day: 'numeric',
								month: 'numeric',
								year: 'numeric'
							};
							const formattedDateTime = postDate.toLocaleDateString('fi-FI', options).replace(/\//g, ' ').replace(',', '');
							return (
								<div className="artcloud-item col-4">
									<div className="artcloud-postImg">
										{displayAuthorImage && authorImage && (
											<img src={authorImage} alt={authorName.alt_text} />
										)}
									</div>
									<div className="artcloud-content" style={{ backgroundColor: backgroundColor, color: textColor }}>
										<div className='artcloud-date-author'><span style={{ color: textColor }}>{displayDateAuthor && formattedDateTime && formattedDateTime}</span><h6 style={{ color: textColor }}>{displayDateAuthor && authorName && authorName} </h6></div>
										<RawHTML>
											{displayDescription && postExcerpt && postExcerpt}
										</RawHTML>
										<a
											style={{ backgroundColor: btnBackgroundColor, color: btnTextColor }}
											className="wp-block-post-excerpt__more-link"
											href={post.link}
										>
											{__('Lue', 'artcloud-blocks')}
										</a>
									</div>
								</div>
							);
						})) : (
						<div className="artcloud-item col-12">
							<p>{__('No posts found for the selected author.', 'artcloud-blocks')}</p>
						</div>
					)}
				</div>
			</div>
		</div>
	);
}
