import { useState, useEffect, useRef } from '@wordpress/element';
import { pagelayerParseHtmlToReact } from '../helpers/html-to-react';

var pagelayer_nav = {};
var eleActive = {}; // TODO: check and remove

export const RenderPrimaryMenuBlock = (props) => {
	const { _props, pl_props, data } = props;
	const { id, atts } = data;
	const { attributes, clientId, setAttributes } = _props;
	const menuHolder = useRef(null);
	const [navMenu, setNavMenu] = useState(null);
	
	const addMenuHtml = (html, render) => {
		setNavMenu( pagelayerParseHtmlToReact(html, _props) );
	}
	
	useEffect( () => {
		const jEle = jQuery(menuHolder.current).closest('#block-'+clientId);
		var win = pagelayerGetCurrentWindow();
		
		pagelayer_primary_menu(jEle);
		
		jQuery(win).on('resize.pl_menu'+clientId, function () {
			pagelayer_primary_menu(jEle);
		})
		
		return (() => {
			jQuery(win).unbind('resize.pl_menu'+clientId);
		});
	}, [ navMenu ]);
	
	useEffect( () => {
	
		var jEle = jQuery(menuHolder.current).closest('#block-'+clientId);;
		var menuID = atts['nav_list'];
		var parMenu = jEle.parent().closest('.pagelayer-wp_menu');
		var inside_mega = '';
		var menu_error = '';
		
		// If we are inside primary menu and have a same menu ID
		if(parMenu.length > 0){
			
			var parMenuID = 0; //pagelayer_get_att(parMenu, 'nav_list');
			
			if(menuID == parMenuID){
				//pagelayer_show_msg('Not allowed same Menu inside the Primary menu widget!', 'warning');
				inside_mega = true;
			
			// If parent menu menuID is empty then we prevent menu inside menu
			}else if(pagelayer_empty(menuID) || pagelayer_empty(parMenuID) ){
				menu_error = 'Primary Menu Holder. Please select the correct menu or parent menu.';
				inside_mega = true;
			}
		
		}
		
		// Set atts for easy rendering in PHP
		setAttributes({'inside_mega': inside_mega});
		
		if(!pagelayer_empty(inside_mega)){
			
			if(pagelayer_empty(menu_error)){
				menu_error = 'Primary Menu Holder. Please select the correct menu.';
			}
			
			setNavMenu( menu_error );
			return;
		}
		
		// Setting default toggle icon. If the icon is empty.
		if(pagelayer_empty(atts['menu_toggle_icon'])){
			atts['menu_toggle_icon'] = 'fas fa-bars';
		}
		
		if( pagelayer_empty(pagelayer_nav[menuID]) ){
			
			// TODO for mega menu 
			var pagelayer_nav_items_list = {}; //pagelayer_get_nav_items(jEle);
			var findPar = jEle.find('.pagelayer-wp_menu-ul').parent();
			
			// Get menu container for the hold place of the menu
			if(findPar.length > 0){
				addMenuHtml(findPar[0].outerHTML, false);
			}
				
			jQuery.ajax({
				url: pagelayer_ajax_url+'&action=pagelayer_fetch_primary_menu&postID='+pagelayer_postID, // Send post id to on live mode
				type: 'post',
				data: {
					pagelayer_nonce: pagelayer_ajax_nonce,
					nav_list: menuID,
					pagelayer_nav_items: pagelayer_nav_items_list,
					'pagelayer-live': 1
				},
				success: function(data) {
					//console.log(data);
					data = pagelayer_apply_megamenu_items(data, menuID, jEle, eleActive);
					pagelayer_nav[menuID] = data;
					addMenuHtml(data);
				}
			});
			
		}else{
			
			var nav_menu = pagelayer_apply_megamenu_items(pagelayer_nav[menuID], menuID, jEle, eleActive);
			
			addMenuHtml(nav_menu);
		}
		
	}, [ attributes ] );
	
	return (
		<>
			<div
				className="pagelayer-wp-menu-holder"
				data-layout={atts?.layout} 
				data-submenu_ind={atts?.submenu_ind} 
				data-drop_breakpoint={atts?.drop_breakpoint}
				ref={menuHolder}
			>
				<div className="pagelayer-primary-menu-bar">
					<i className={atts?.menu_toggle_icon}></i>
				</div>
				<div 
					className={`pagelayer-wp-menu-container pagelayer-menu-type-${atts.layout} pagelayer-menu-hover-${atts.pointer} ${atts.m_animation} ${atts.slide_style}`}
					data-align={atts?.align}
				>
					<div className="pagelayer-wp_menu-close">
						<i className="fas fa-times"></i>
					</div>
					{ navMenu }
				</div>
			</div>
		</>
	)
}

// TODO: check and remove
var pagelayer_menus_items_list = {};

function pagelayer_apply_megamenu_items(html, menuID, menuEle, eleActive){
	
	if(pagelayer_empty(pagelayer_menus_items_list[menuID])){
		return html;
	}
	
	var menu_data = jQuery('<div>').html(html);	
	var $elements = pagelayer_menus_items_list[menuID];
	
	
	for($e in $elements){
		var savedHTML = '';
		
		if(pagelayer_empty($elements[$e]['pagelayer_content'])){
			 continue;
		}
		
		var mID = $elements[$e]['ID'];

		savedHTML = $elements[$e]['pagelayer_content'];
		
		menu_data.find('.pagelayer-mega-editor-'+mID).html(savedHTML[0].outerHTML);
	}
		
	return menu_data.html();
}