import { useState, useEffect } from '@wordpress/element';

export const RenderPostsBlock = (props) => {
	const { _props, pl_props, tag, data } = props;
	const { id, atts } = data;
	const { attributes } = _props;
	
	const [cachedResponses, setCachedResponses] = useState([]);
	const [postHTML, setPostHTML] = useState('');
	
	useEffect(() => {
		const post = {};
		post['pagelayer_nonce'] = pagelayer_ajax_nonce;
		if (atts['count']) post['posts_per_page'] = atts['count'];
		if (atts['show_thumb']) post['show_thumb'] = atts['show_thumb'];
		if (atts['thumb_size']) post['thumb_size'] = atts['thumb_size'];
		if (atts['show_content']) post['show_content'] = atts['show_content'];
		if (atts['show_title']) post['show_title'] = atts['show_title'];
		if (atts['more']) post['more'] = atts['more'];
		if (atts['btn_type']) post['btn_type'] = atts['btn_type'];
		if (atts['size']) post['size'] = atts['size'];
		if (atts['icon_position']) post['icon_position'] = atts['icon_position'];
		if (atts['icon']) post['icon'] = atts['icon'];
		if (atts['show_more']) post['show_more'] = atts['show_more'];
		if (atts['meta_sep']) post['meta_sep'] = atts['meta_sep'];
		if (atts['exc_length']) post['exc_length'] = atts['exc_length'];
		if (atts['post_type']) post['post_type'] = atts['post_type'];
		if (atts['posts_order']) post['order'] = atts['posts_order'];
		if (atts['inc_term']) post['term'] = atts['inc_term'];
		if (atts['inc_author']) post['author_name'] = atts['inc_author'];
		if (atts['exc_term']) post['exc_term'] = atts['exc_term'];
		if (atts['exc_author']) post['exc_author'] = atts['exc_author'];
		if (atts['offset']) post['offset'] = atts['offset'];
		if (atts['ignore_sticky']) post['ignore_sticky'] = atts['ignore_sticky'];
		if (atts['orderby']) post['orderby'] = atts['orderby'];
		if (atts['by_period']) post['by_period'] = atts['by_period'];
		if (atts['before_date']) post['before_date'] = atts['before_date'];
		if (atts['after_date']) post['after_date'] = atts['after_date'];
		if (atts['thumb_img_type']) post['thumb_img_type'] = atts['thumb_img_type'];

		var img_size = data.tmp['def_thumb_img-' + atts['thumb_size'] + '-url'];
		if (atts['def_thumb_img']) post['def_thumb_img'] = pagelayer_empty(img_size) ? data.tmp['def_thumb_img-url'] : img_size;

		if(!pagelayer_empty(atts['meta'])) {
			
			var meta_arr = atts['meta'].split(',');
			jQuery.each(meta_arr, function (index, value) {
				post[value] = value;
			});
		}
		
		const stringifiedPost = JSON.stringify(post);

		// Check if the response is already cached
		const cachedResponse = cachedResponses.find(
			(cached) => JSON.stringify(cached.post) === stringifiedPost
		);

		if (cachedResponse) {
			setPostHTML(cachedResponse.data);			
		} else {
			// If not cached, make the AJAX call
			jQuery.ajax({
				url: pagelayer_ajax_url + 'action=pagelayer_posts_data',
				type: "post",
				data: post,
				success: function (data) {
					setPostHTML(data);
					
					// Cache the response for future use
					setCachedResponses((prevResponses) => [
						...prevResponses,
						{ post: post, data: data },
					]);

				},
			});
		}

	}, [attributes]);
	
	const destroySlider = (jEle) => {
		pagelayer_owl_destroy(jEle, '.pagelayer-posts-container');
		jEle.find('.pagelayer-posts-container').removeClass(function (index, className) {
			const regex = /pagelayer-owl-\S+/g;
			const matches = className.match(regex);
			return matches ? matches.join(" ") : "";
		});
	}
	
	useEffect(() => {
		var jEle = pagelayer_query(`.p-${id}`);
		
		if (atts['enable_slider']) {
			setTimeout(() => {
				destroySlider(jEle);
				pagelayer_pl_posts(jEle);
			}, 50);
			
			return;
		}
    
		destroySlider(jEle);
		
	}, [attributes, postHTML]);
	
	return (
		<>
			<div className="pagelayer-posts-container" dangerouslySetInnerHTML={{__html: postHTML}} />
			{ atts?.infinite_types &&
				<div className="pagelayer_load_button" data-text={ atts['infinite_final'] }>
					<a data-max={atts?.max_pages} className={`pagelayer-btn-holder pagelayer-btn-load pagelayer-ele-link ${atts['infinite_btn_type']} ${atts['infinite_btn_size']} ${atts['infinite_btn_size']} ${atts?.load_btn_icon_position}`}>
						{atts?.load_btn_icon && <i className={`${atts['load_btn_icon']} pagelayer-btn-load-icon`}></i> }
						{atts?.infinite_text && <span className="pagelayer-btn-load-text" >{atts['infinite_text']}</span> }
						{atts?.load_btn_icon && <i className={`${atts['load_btn_icon']} pagelayer-btn-load-icon`}></i> }
					</a>
					<div className="pagelayer-loader-holder" >
						<i className="fa fa-spinner fa-spin fa-3x fa-fw" aria-hidden="true"></i>
					</div>
				</div>
			}
		</>
	);
};
