import { __ } from "@wordpress/i18n";
import { useState, useEffect, useRef } from '@wordpress/element';
import { parse } from '@wordpress/blocks';
import { dispatch } from '@wordpress/data';

// logo is not loading check that out
const Logo = pagelayer_url + "/images/pagelayer-logo-19.png";
const Loader = pagelayer_url + "/images/Spinner-3.gif";

export const PagelayerLibrary = () => {

	const [resultSet, setResultSet] = useState({});
	const [activeButton, setActiveButton] = useState('header');
	const [selectedTags, setSelectedTags] = useState('');
	const [tagList, setTagList] = useState({});
	const [isLoading, setIsLoading] = useState(false);
	const [activeTag, setActiveTag] = useState([]);
	const [numCols, setNumCols] = useState(3);
	const [itemsList, setItemsList] = useState([]);
	const [itemsToRender, setItemsToRender] = useState([]);
	const [tagLengths, setTagLengths] = useState({});

	const sectionsType = {
		section: __('sections'),
		header: __('Header'),
		footer: __('Footer'),
		page: __('Page'),
	};

	useEffect(() => {
		// Find the number of cols
		const bodyWidth = window.innerWidth;
		if (bodyWidth >= 1500) {
			setNumCols(4);
		} else if (bodyWidth >= 992) {
			setNumCols(3);
		} else if (bodyWidth >= 768) {
			setNumCols(2);
		} else if (bodyWidth >= 360) {
			setNumCols(1);
		}
	}, []);

	// Insert section in pages
	useEffect(() => {
		jQuery('.pagelayer-section-holder').on('click', function (e) {
			var jEle = jQuery(e.target).closest('.pagelayer-section-item');
			if (jEle.length < 1 || jEle.find('.pagelayer-section-pro-req').length > 0) {
				return;
			}
			e.preventDefault();
			var sectionId = jEle.attr('pagelayer-add-section-id');
			setIsLoading(true);
			// Do shortcode the content
			jQuery.ajax({
				url: pagelayer_ajax_url + '&action=pagelayer_get_section_blocks',
				type: 'POST',
				data: {
					'pagelayer_nonce': pagelayer_ajax_nonce,
					'pagelayer_section_id': sectionId,
				},
				success: function (data) {
					try {
						var data = JSON.parse(data);
						if (!pagelayer_empty(data['error'])) {
							console.log('Error getting the section');						
							jQuery('.pagelayer-library-modal-container').hide();
							setIsLoading(false);
							return;
						}
						var blockContent = parse(data.code);
						// TODO: for insert point
						// Insert the block into the editor
						dispatch('core/block-editor').insertBlocks(blockContent);

					} catch (e) {
						console.log('Error getting the section');
						jQuery('.pagelayer-library-modal-container').hide();
						setIsLoading(false);
						return;
					}
				},
				complete: function () {
					jQuery('.pagelayer-library-modal-container').hide();
					setIsLoading(false);
				}
			});
		});

		return (() => {
			jQuery(".pagelayer-section-holder").unbind('click');
		});
	});

	// Load section by type
	useEffect(() => {
		if (activeButton in resultSet && !pagelayer_empty(resultSet[activeButton])) {
			setItemsToRender({ ...resultSet[activeButton]["list"] });
			return;
		}
		setIsLoading(true);
		const apiUrl = `https://api.pagelayer.com/library.php?give=${activeButton}`;
		// Use the fetch API to make the GET request to the API
		fetch(apiUrl)
			.then((response) => {
				if (!response.ok) {
					throw new Error("Network response was not ok");
				}
				return response.json();
			})
			.then((jsonData) => {
				setResultSet({ ...resultSet, [activeButton]: jsonData });
				setItemsToRender({ ...jsonData["list"] });
				setTagList(jsonData.tags);
				setIsLoading(false);

			})
			.catch((error) => {
				console.error("Error fetching data:", error);
				setIsLoading(false);
			});

	}, [activeButton]);

	// Render section in modal
	useEffect(() => {
		var scrollAccessed = false;
		const showResult = () => {
			var mEle = jQuery('.pagelayer-library-modal-container');
			var tester = mEle.find('.pagelayer-section-is-visible');

			if (!(activeButton in resultSet) || !pagelayer_isElementInView(tester, mEle)) {
				return;
			}
			
			if(Object.keys(itemsToRender).length === 0 || scrollAccessed){
				return;
			}
			
			scrollAccessed = true;

			const itemsRender = [...itemsList];
			const newItemsToRender = { ...itemsToRender };
			let i = 0;
			for (const id in itemsToRender) {
				if (i >= numCols * 5) {
					break;
				}

				const col = i % numCols;

				if (!(col in itemsRender)) {
					itemsRender[col] = [];
				}

				itemsRender[col].push(id);
				delete newItemsToRender[id];
				i++;
			}

			setItemsToRender(newItemsToRender);
			setItemsList(itemsRender);

			scrollAccessed = false;
		}

		showResult();
		// Scroll will is set to pagelayer-section-modal-body 
		jQuery('.pagelayer-section-modal-body').on('scroll', showResult);

		return (() => {
			jQuery('.pagelayer-section-modal-body').unbind('scroll');
		});
	}, [itemsToRender]);

	// Get the number of items inside the each taglist and append the number
	useEffect(() => {
		Object.keys(tagList).forEach((tag) => {
			tagLengths[tag] = tagList[tag].length;
		});
		setTagLengths(tagLengths);
	}, [tagList]);

	// On change the Type
	const handleButtonClick = (buttonName) => {
		// empty previous active tags
		setActiveTag([]);
		
		if (activeButton === buttonName) {
			return;
		}
		setItemsList([]);
		setActiveButton(buttonName);

		if (!(buttonName in resultSet)) {
			return;
		}

		setTagList(resultSet[buttonName].tags);
	};
	// set the default list when the active tag array is empty
	useEffect(() => {
		if (Object.keys(tagList).length > 0 && activeTag.length == 0) {
			if (activeButton in resultSet && !pagelayer_empty(resultSet[activeButton])) {
				setItemsToRender({ ...resultSet[activeButton]["list"] });
			}
		}
	}, [activeTag])

	// On change set the multiple tags if selected
	const handleTagClick = (tag, index) => {
		const isActive = activeTag.includes(tag);
		const newActiveTags = isActive ? activeTag.filter((activeTag) => activeTag !== tag) : [...activeTag, tag];
		const newItems = {};
		newActiveTags.forEach((activeTag) => {
			if (activeTag in tagList) {
				tagList[activeTag].forEach((id) => {
					newItems[id] = id;
				});
			}
		});
		setItemsList([]);
		setActiveTag(newActiveTags);
		setItemsToRender(newItems);
	};

	return (
		<>
			<PagelayerLibraryButton />
			<div className="pagelayer-library-modal-container" style={{ display: "none" }}>
				<nav className="pagelayer-library-modal-nav">
					<button>
						<img src={Logo} alt="Pagelayer Logo" />
						{__('Pagelayer Library')}
					</button>
					<div className='pagelayer-library-modal-ul-container'>
						<ul className='pagelayer-library-modal-ul'>
							{Object.keys(sectionsType).map((section, index) => {
								return (<li>
									<button
										className={activeButton === section ? "pagelayer-active-modal-btn" : ""}
										onClick={() => handleButtonClick(section)}
									>
										{sectionsType[section]}
									</button>
								</li>);
							})}
						</ul>
					</div>
					<span className="pagelayer-library-modal-close">&times;</span>
				</nav>

				<div className="pagelayer-library-modal-content" id="modal">
					<div className="pagelayer-library-modal-tags" >
						<div className="pagelayer-library-modal-tag-div">
							<input type="text" value={selectedTags} style={{ border: "none", backgroundColor: "#724c8717", padding: "7px", width: "212px", borderRadius: "0px" }} onChange={(e) => setSelectedTags(e.target.value)} placeholder="Search" />
						</div>
						<div className="pagelayer-library-modal-tag-list">
							{Object.keys(tagList).map((tags, index) => {

								const displayTag = selectedTags ? tags.includes(selectedTags) : true;
								const isTagActive = activeTag.includes(tags);
								const borderBottomStyle = isTagActive ? 'pagelayer-tag-style-active' : '';

								return (
									displayTag && (
										<p
											key={index}
											onClick={() => handleTagClick(tags, index)}
											style={{ cursor: 'pointer' }}
											className={borderBottomStyle}
										>
											{/* Tags with Number */}
											{`${tags} (${tagLengths[tags]})`}
										</p>
									)
								);
							})}

						</div>
					</div>
					<div className="pagelayer-section-modal-body" style={isLoading ? { overflow: 'hidden' } : { overflow: "auto" }}>
						{itemsList.map((item) => {

							if (!(activeButton in resultSet)) {
								return;
							}
							return (<div className="pagelayer-section-holder" pagelayer-section-type={activeButton}>
								{item.map((id) => {
									return (<div
										key={id}
										className={`pagelayer-section-item`}
										pagelayer-add-section-id={id}
									>
										<img
											src={`${resultSet[activeButton]["image_url"]}${id}/screenshot.jpg`}
											alt="Pagelayer code screenshot"
											loading="lazy"
										/>
										{!pagelayer_empty(resultSet[activeButton]["list"][id]) && pagelayer_empty(pagelayer_pro) && (
											<>
												<div className="pagelayer-section-pro-req">{__('Pro')}</div>
												<div className="pagelayer-section-pro-txt">
													{__('This feature is a part of')}
													<a href={pagelayer_pro_url} target="_blank">{pagelayer_pro_txt}</a>
													{__('You will need purchase')}
													<a href={pagelayer_pro_url} target="_blank">{pagelayer_pro_txt}</a>
													{__('to use this feature.')}
												</div>
											</>
										)}
									</div>
									)
								})}
							</div>
							)
						})}
						<div className="pagelayer-section-is-visible"></div>
					</div>
					{isLoading && (
						<div className="pagelayer-library-loader"><img src={Loader} alt="Loading..." /></div>
					)}
					{isLoading && (
						<div className="pagelayer-add-section-modal-overlay">
							<div className="pagelayer-section-wait">
								<div className="pagelayer-loader">
									<div className="pagelayer-percent-parent"></div>
								</div><br />
								<span>{__('Please wait a moment')}</span>
							</div>
						</div>
					)}
				</div>
			</div>
		</>
	);
};



export const PagelayerLibraryButton = () => {

	useEffect(() => {

		var button = jQuery("#pagelayer-editor-button-modal");
		var g = jQuery(".edit-post-header-toolbar");

		if (g.length < 1) {
			return;
		}

		button.detach();
		g.parent().append(button);
		button.show();

		jQuery('#pagelayer-library-modal-btn').on('click', function (e) {
			e.preventDefault();
			jQuery('.pagelayer-library-modal-container').show();
		});

		jQuery('.pagelayer-library-modal-close').click(function () {
			jQuery('.pagelayer-library-modal-container').hide();
		});

		return (() => {
			jQuery("#pagelayer-library-modal-btn").unbind('click');
			jQuery(".pagelayer-library-modal-close").unbind('click');
		});
	});

	return (
		<div id="pagelayer-editor-button-modal" style={{ marginLeft: '15px' }}>
			<a
				id="pagelayer-library-modal-btn"
				className="button button-primary button-large"
				style={{
					height: 'auto',
					padding: '4px 8px',
					fontSize: '13px',
					display: 'flex',
					alignItems: 'center',
					width: 'max-content',
				}}
			>
				<img src={`${pagelayer_url}/images/pagelayer-logo-40.png`} align="top" width="22" style={{ marginRight: '4px' }} />
				<span>{__('Library')}</span>
			</a>
		</div>
	);
};


