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

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

// Local Dependencies.
import { ListingGridEditProps } 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 {ListingGridEditProps} props React component props.
 *
 * @returns {ReactElement}
 */
const ListingGridEdit = (props: ListingGridEditProps): ReactElement => {
	const {
		attrs,
		id,
		name,
		elements,
	} = props;

	const normalizedId = String( id || '' );
	const currentBlockId = attrs?._block_id?.innerContent?.desktop?.value;
	const currentElementId = attrs?._element_id?.innerContent?.desktop?.value;
	const safeId = (
		currentBlockId && currentBlockId !== 'false' ? currentBlockId
			: ( currentElementId && currentElementId !== 'false' ? currentElementId : normalizedId )
	);

	const attributesForRender = {
		...attrs,
		_block_id: {
			innerContent: {
				desktop: {
					value: safeId,
				},
			},
		},
		_element_id: {
			innerContent: {
				desktop: {
					value: safeId,
				},
			},
		},
	};

	return (
		<ModuleContainer
			attrs={attributesForRender}
			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/listing-grid"
						attributes={ attributesForRender }
					/>
				</>
			}
		</ModuleContainer>
	);
}

export {
	ListingGridEdit,
};
