// External Dependencies.
import React, { ReactElement } from 'react';

// Divi Dependencies.
import {
	ModuleContainer,
	ElementComponents,
} from '@divi/module';

// Local Dependencies.
import { DynamicTermsEditProps } from './types';
import { ModuleStyles } from './styles';
import ServerSideRender from '../../server-side-render';
import { ModuleScriptData } from './module-script-data';
import { moduleClassnames } from './module-classnames';

declare global {
	interface Window {
		JetEngineDiviViews: any;
	}
}

/**
 * Static Module edit component of visual builder.
 *
 * @since ??
 *
 * @param {DynamicImageEditProps} props React component props.
 *
 * @returns {ReactElement}
 */
const DynamicTermsEdit = (props: DynamicTermsEditProps): ReactElement => {
	const {
		attrs,
		id,
		name,
		elements,
	} = props;

	let object = window?.JetEngineDiviViews?.object_id;
	let listing = { ...(window?.JetEngineDiviViews?.settings || {}) } as Record<string, unknown>;
	const context = ( props as any )?.context || {};

	if ( context?.queryId ) {
		object = context.postId;
		listing = {
			listing_source: 'posts',
			listing_post_type: context.postType,
		};
	}

	delete listing.component_controls_list;
	delete listing.component_style_controls_list;

	const attributesForRender: Record<string, unknown> = {
		...( attrs as Record<string, unknown> ),
	};

	const loopObjectRaw = ( attributesForRender as any )?.jet_loop_object;
	const loopObjectFromNested = ( loopObjectRaw && typeof loopObjectRaw === 'object' )
		? loopObjectRaw?.innerContent?.desktop?.value
		: undefined;

	const normalizedLoopObject = (
		typeof loopObjectRaw === 'string'
			? loopObjectRaw
			: ( typeof loopObjectFromNested === 'string'
				? loopObjectFromNested
				: '$variable({"type":"content","value":{"name":"jet_loop_object"}})$'
			)
	);
	attributesForRender.jet_loop_object = normalizedLoopObject;

	return (
		<ModuleContainer
			attrs={ attributesForRender as any }
			elements={elements}
			id={id}
			name={name}
			stylesComponent={ModuleStyles}
			classnamesFunction={moduleClassnames}
			scriptDataComponent={ModuleScriptData}
		>
			{elements.styleComponents({
				attrName: 'module',
			})}
			{
				<>
					<ElementComponents
						attrs={attrs?.module?.decoration ?? {}}
						id={id}
					/>
					<ServerSideRender
						block="jet-engine-divi/dynamic-terms"
						attributes={ attributesForRender }
						queryArgs={ {
							object,
							listing,
						} }
					/>
				</>
			}
		</ModuleContainer>
	);
}

export {
	DynamicTermsEdit,
};
