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

export default function Edit({ attributes, setAttributes }) {
	const { title, numberOfItems, orderBy, order, selectedStyle, displayFeaturedImage, displayDescription, displayDateAuthor, postType, categories, selectedTitles, textColor, backgroundColor, btnBackgroundColor, btnTextColor } = attributes;
	const [isOpen, setOpen] = useState(false);
	const openModal = () => setOpen(true);
	const closeModal = () => setOpen(false);
	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 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 onChangeTitle = (value) => {
		setAttributes({ title: value });
	};
	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 displayDateAuthorChange = (value) => {
		setAttributes({ displayDateAuthor: value });
	};

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

	const onNumberOfItemsChange = (value) => {
		setAttributes({ numberOfItems: value });
	};
	// const onSelectTitles = (event) => {
    //     event.preventDefault(); 

    //     const selectedTitles = Array.from(event.target.elements)
    //         .filter((el) => el.type === 'checkbox' && el.checked)
    //         .map((el) => el.value);

    //     const titleObjs = selectedTitles.map((title) => {
    //         const foundPost = allpostTitles.find((post) => post.title === title);
    //         return foundPost ? foundPost : { id: null, title: title };
    //     });

    //     setAttributes({ selectedTitles: titleObjs });
    // };
	const onSelectTitles = (event) => {
        event.preventDefault(); 

        const selectedTitles = Array.from(event.target.elements)
            .filter((el) => el.type === 'checkbox' && el.checked)
            .map((el) => el.value);

        const titleObjs = selectedTitles.map((title) => {
            const foundPost = allpostTitles.find((post) => post.title === title);
            return foundPost ? foundPost : { id: null, title: title };
        });

        setAttributes({ selectedTitles: titleObjs });
    };
	const onChangeStyle = (value) => {
		setAttributes({ selectedStyle: value });
	};
	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 = [
		'page', 'attachment', 'nav_menu_item',
		'wp_block', 'wp_template', 'wp_template_part', 'wp_navigation'
	];
	//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 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 Image', 'artcloud-blocks')}
						checked={displayFeaturedImage}
						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}
						orderBy={orderBy}
						onOrderByChange={(value) => setAttributes({ orderBy: value })}
						order={order}
						onOrderChange={(value) => setAttributes({ order: value })}
					/>
					
					<PanelBody>
						<Button variant="secondary" onClick={openModal}>
							Open Modal
						</Button>
						{isOpen && (
							<Modal title="This is my modal" onRequestClose={closeModal}>
							<form onSubmit={onSelectTitles}>
							<ul>
							{allpostTitles.map(titleObj => titleObj.title && <li><input type="checkbox" value={titleObj.title} /> {titleObj.title}</li>)}
							</ul>
							<Button variant="primary" type="submit">Submit</Button>
							</form>	
							<Button variant="secondary" onClick={closeModal}>
									My custom close button
								</Button>

							</Modal>
						)}
					</PanelBody>
				</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')}
					allowedFormats={[]}
					value={title}
					onChange={onChangeTitle}
				/>
				<div className='row'>

					{sortedItems &&
						sortedItems.map((post) => {
							const postImage =
								post._embedded &&
								post._embedded['wp:featuredmedia'] &&
								post._embedded['wp:featuredmedia'].length > 0 &&
								post._embedded['wp:featuredmedia'][0];
							const authorName = post?._embedded?.['author']?.[0]?.name ?? post.speaker_name;
							const postContent = post.excerpt.rendered;
							const postExcerpt = selectedStyle === 'style1' ? postContent.split(' ').slice(0, 8).join(' ') : postContent.split(' ').slice(0, 25).join(' ');
							const postDate = new Date(post.date);

							const options1 = {
								day: 'numeric',
								month: 'numeric',
								year: 'numeric',
							};
							const options2 = {
								day: 'numeric',
								month: 'numeric',
								year: 'numeric',
								hour: 'numeric',
								minute: 'numeric',
								second: 'numeric',
								hour24: true // Set this to true for 12-hour clock format
							};
							const selectedOptions = selectedStyle === 'style1' ? options1 : options2;
							const formattedDateTime = postDate.toLocaleDateString('fi-FI', selectedOptions).replace(/\//g, ' ').replace(',', '');
							const dateAuthor = formattedDateTime + ' | ' + authorName;
							return (
								<div className='artcloud-item col-4' style={{ backgroundColor: backgroundColor, color: textColor }}>
									{selectedStyle === 'style1' && (
										<React.Fragment>
											{displayFeaturedImage && postImage && (
												<div className="artcloud-postImg">
													<img
														src={postImage.media_details.sizes.full.source_url}
														alt={postImage.alt_text}
													/>
												</div>
											)}
											<div className="artcloud-content">
												{displayDateAuthor && dateAuthor &&
													<h6> {(dateAuthor)} </h6>
												}
												<h3 style={{ color: textColor }}>{post.title.rendered}</h3>
												<RawHTML>{displayDescription && postExcerpt && (
													postExcerpt
												)}</RawHTML>
												<a
													style={{ backgroundColor: btnBackgroundColor, color: btnTextColor }}
													className="wp-block-post-excerpt__more-link" href={post.link}>{__('Lue lisää', 'artcloud-blocks')}</a>
											</div>
										</React.Fragment>
									)}
									{selectedStyle === 'style2' && (
										<React.Fragment>
											{displayFeaturedImage && postImage && (
												<div className="artcloud-postImg">
													<img
														src={postImage.media_details.sizes.full.source_url}
														alt={postImage.alt_text}
													/>
												</div>
											)}
											<div className="artcloud-content">
												{displayDateAuthor && dateAuthor &&
													<h6> {(dateAuthor)}</h6>}
												<h5 style={{ color: textColor }}>{post.title.rendered}</h5>
												<RawHTML>{displayDescription && postExcerpt && (
													postExcerpt
												)}</RawHTML> </div>
										</React.Fragment>
									)}
								</div>
							);
						})}
				</div>
			</div>
		</div>
	);
}
