import { __ } from '@wordpress/i18n';
import { LabelControl } from './label';
import { useState, useRef, useEffect } from '@wordpress/element';
import {
__experimentalLinkControl as LinkControl,
__experimentalLinkControlSearchInput as LinkControlSearchInput
} from '@wordpress/blockEditor';

const { internal_linking_nonce } = pagelayer_config;

// TODO: re-arrang the content
export const CustomLinkControl = (props) =>{
	
	// TODO further improve
	const { attributes, prop, value, setAttributes } = props;
	const { name } = prop['c'];
	const tmpAtts = attributes?.tmpAtts ?  attributes.tmpAtts : {};
	
	const [values, setValues] = useState({});
	const [settingOpt, setSettingOpt] = useState(false);
	const [toggleSetting, setToggleSetting] = useState(false);
	const [link, setLink] = useState('');
	const holderRef = useRef(null);
	
	const getLinkVal = function(val){
		
		if(typeof val === 'object' && pagelayerLength(val) == 1 && 'link' in val){
			return val['link'];
		}
		
		return val;
	}
	
	const setAttributesHandler = (setValue) => {
		
		var updatedValues = {...values};
		
		for(var key in setValue){
						
			if(!pagelayer_empty(setValue[key])) {
				updatedValues[key] = setValue[key];
				continue;
			}
			
			delete updatedValues[key];
		}
	
		var linkValue = getLinkVal(updatedValues);
		linkValue = pagelayer_empty(linkValue) ? '' : linkValue;
				
		setValues(updatedValues);
		setAttributes({[name]: linkValue});
	}
	
	useEffect(() => {
		
		// Show link options?
		if('selector' in prop) {
			setSettingOpt(true);
		}
		
		var preVal = attributes[name];
				 
		// Previously saved values
		if (typeof preVal != 'object') {
			preVal = { 'link': preVal }
		}

		const linkValue = (name in tmpAtts) ? tmpAtts[name] : preVal?.link;
		
		if(!pagelayer_empty(linkValue)){
			setLink(linkValue);
		}
		
		setAttributesHandler(preVal);
	}, [prop]);
	
	useEffect(() => {
		var listWrap = jQuery(holderRef.current).find('.pagelayer-elp-link-list');
		listWrap.on('click', function(e){
			e.stopPropagation();
			
			var lEle = jQuery(e.target).closest('.pagelayer-elp-link-item');
			
			// IF item not found
			if(lEle.length < 1){
				return;
			}
			
			var perma = lEle.attr('data-permalink');
			var ID = lEle.attr('data-id');
			
			// Save and Render
			jQuery(holderRef.current).find('.pagelayer-elp-link').val(perma);
			
			setAttributesHandler({
				link: ID,
			});
			
			// save tmp value
			const tmp = {
				...tmpAtts,
				[name]: perma
			};
			
			setAttributes({ tmpAtts: tmp });
			
			setLink(perma);
			listWrap.hide();
			
			// Show ID
			// addID(ID);
		});
		
		jQuery(document).on('click', function(e){
			listWrap.hide();
		});
	
	}, []);

	const linkChangeHandler = (event) => {
		var linkVal = event.target.value;
		setLink(linkVal);
		setAttributesHandler({
			link: linkVal
		})
		
		// save tmp value
		const tmp = {
			...tmpAtts,
			[name]: linkVal
		};
		
		setAttributes({ tmpAtts: tmp });
		
		// Remove ID Holder
		//addID();
	}
	
	const handleCheckboxChange = (event) => {
		const { checked } = event.target;
		const checkboxName = event.target.name;
		var ischecked = checked ? true : false;		
		
		setAttributesHandler({[checkboxName]: ischecked});
	};
	
	var time = {};
	
	// Set a Link
	const linkInputeHandler = (e) => {
		e.stopPropagation();
		
		const val = e.target.value;
		
		var listWrap = jQuery(holderRef.current).find('.pagelayer-elp-link-list');
		
		if(!listWrap.is(':visible')){
			listWrap.show();
		}
		
		clearTimeout(time);
		time = setTimeout(function(){

			jQuery.ajax({
				url: pagelayer_ajax_url,
				type: 'post',
				data:{
					'action' : 'wp-link-ajax',
					'_ajax_linking_nonce' : internal_linking_nonce,
					'search' : val,
				},
				success: function(response) {
					
					var data = jQuery.parseJSON(response);
					var html = '';
					//console.log('Link Data');console.log(response);
					
					if(pagelayer_empty(data)){
						html = __('Custom Url');
						// Remove ID Holder
						// addID();
					}else if(typeof data === 'object'){
						
						for(var key in data){
							var vals = data[key];
							html += '<div class="pagelayer-elp-link-item"  data-id="'+vals['ID']+'" data-permalink="'+vals['permalink']+'">'+
								'<div class="pagelayer-elp-link-title">'+
									'<span class="pagelayer-elp-link-item-title" title="'+vals['title']+'">'+vals['title']+'</span>'+
									'<span class="pagelayer-elp-link-item-perma" title="'+vals['permalink']+'">'+vals['permalink']+'</span>'+
								'</div>'+
								'<div class="pagelayer-elp-link-info">'+
									'<span title="'+vals['info']+'">'+vals['info']+'</span>'+
								'</div>'+
							'</div>';
						}
					}
					
					listWrap.html(html);
				},
				fail: function(data) {
					listWrap.html('Some error occured in getting the link data');
				}
			});
			
		}, 200);
		
	};
	
	return (
		<div className="components-base-control pagelayer-base-control" ref={holderRef}>
			<LabelControl {...props} />
			<div className={`pagelayer-elp-link-div pagelayer-elp-input-icon ${settingOpt ? '' : 'pagelayer-elp-link-no-addons'}`}>
				<input
					className="pagelayer-elp-link"
					type="text"
					value={link}
					onChange={linkChangeHandler}
					onInput={linkInputeHandler}
				/>
				<i className="pli pli-service pagelayer-elp-link-icon" title={'link_options'} onClick={ () => setToggleSetting(!toggleSetting)}></i>
				<div className="pagelayer-elp-link-list">
				{/* Render the list items here */}
				</div>
				{settingOpt && toggleSetting && (
					<div className="pagelayer-elp-link-addons">
						<div className="pagelayer-elp-link-cb-div">
							<div className="pagelayer-elp-link-label-div">
								<label className="pagelayer-elp-link-label">{ __('Open link in new window (tab)') }</label>
							</div>
							<div>
								<input
									type="checkbox"
									name="target"
									className="pagelayer-elp-checkbox"
									checked={!pagelayer_empty(values['target'])}
									onChange={handleCheckboxChange}
								/>
							</div>
						</div>
						<div className="pagelayer-elp-link-cb-div" >
							<div className="pagelayer-elp-link-label-div">
								<label className="pagelayer-elp-link-label">{ __('Add Nofollow') }</label>
							</div>
							<div>
								<input type="checkbox"
									name="rel"
									className="pagelayer-elp-checkbox" 
									checked={!pagelayer_empty(values['rel'])}
									onChange={handleCheckboxChange}
								/>
							</div>
						</div>
						<div className="pagelayer-elp-link-ca" >
							<div className="pagelayer-elp-link-label-div">
								<label className="pagelayer-elp-link-label">{ __('Custom Attributes') }</label>
							</div>
							<input 
								type="text" 
								className="pagelayer-elp-text" 
								placeholder="key = value" 
								value={values?.attrs}
								onChange={(event) => setAttributesHandler({'attrs': event.target.value})}
							/>
							<p className="pagelayer-elp-link-desc">
								{ __('Setting custom attribute for link. ')}
								<strong>{ __('attribute = value')}</strong>
								{ __('In this way the attribute and its value can be added. Separate key-value pairs using')}
								<strong> { __('semicolon ;')}</strong>.
							</p>
						</div>
					</div>
				)}
			</div>
		</div>
	);
}