/**
 * WordPress dependencies
 */
import { useSelect, useDispatch } from '@wordpress/data';
import {
	store as blocksStore,
} from '@wordpress/blocks';
import {
	useBlockProps,
	store as blockEditorStore,
} from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import DirectoryLayoutSelection from './directory-layout-selection';
import { getTemplate } from '../templates';

export default function UserDirectoryPlaceholder({
	attributes,
	clientId,
	name,
	setAttributes,
}) {
	const blockProps = useBlockProps();

	const { blockType } = useSelect(
		(select) => {
			const { getBlockType } = select(blocksStore);
			return {
				blockType: getBlockType(name),
			};
		},
		[name]
	);

	const { replaceInnerBlocks } = useDispatch(blockEditorStore);

	// Layout templates are now centralized in templates/index.js
	const getLayoutTemplate = (layoutName) => {
		return getTemplate(layoutName);
	};

	// Helper function to convert template to blocks safely (same as in user-directory-content.js)
	const convertTemplateToBlocks = (template, depth = 0) => {
		if (!Array.isArray(template)) {
			return [];
		}

		if (typeof wp === 'undefined' || !wp.blocks || !wp.blocks.createBlock) {
			return [];
		}

		// Prevent infinite recursion
		if (depth > 10) {
			console.warn('Directory: Maximum recursion depth reached, stopping template conversion');
			return [];
		}

		const result = [];

		template.forEach(item => {
			if (!Array.isArray(item) || item.length === 0) {
				return;
			}

			const [blockName, attributes = {}, innerContent = []] = item;

			if (typeof blockName !== 'string') {
				return;
			}

			// Skip insertion point markers - they should have been replaced with actual blocks by now
			if (blockName === 'wpuf-ud/unmatched-blocks') {
				console.warn('Directory: Found unmatched-blocks marker in convertTemplateToBlocks - this should not happen');
				return;
			}

			try {
				// Convert inner content to blocks recursively
				const innerBlocks = Array.isArray(innerContent) ? convertTemplateToBlocks(innerContent, depth + 1) : [];

				const block = wp.blocks.createBlock(blockName, attributes, innerBlocks);
				
				if (block) {
					result.push(block);
				}
			} catch (error) {
				console.warn('Failed to create block:', blockName, error);
			}
		});

		return result;
	};

	// Handle layout selection for initial placeholder
	const handleLayoutSelection = (layoutName, templateName) => {
		// Set attributes
		setAttributes({
			hasSelectedLayout: true,
			selectedLayout: layoutName,
			directory_layout: layoutName
		});

		// Handle table layout differently - it's settings-driven without inner blocks
		if (layoutName === 'table') {
			// For table layout, clear all inner blocks since it's settings-driven
			replaceInnerBlocks(clientId, [], false);
			return;
		}

		// Get the actual template from layout name
		const template = getLayoutTemplate(layoutName);

		// Replace inner blocks with the new template
		if (template && template.length > 0) {
			try {
				// Use the proper template conversion function
				const blocks = convertTemplateToBlocks(template);

				if (blocks && blocks.length > 0) {
					replaceInnerBlocks(clientId, blocks, false);
				}
			} catch (error) {
				console.error('Error creating blocks from template:', error);
			}
		} else if (layoutName === 'blank') {
			// For blank template, clear blocks and let the user add their own
			replaceInnerBlocks(clientId, [], false);
		}
	};

	// Don't render if we're switching layouts (that should be handled by UserDirectoryContent)
	const isSwitchingLayout = attributes.isSwitchingLayout || false;

	if (isSwitchingLayout) {
		return null; // Let UserDirectoryContent handle this
	}

	return (
		<div {...blockProps}>
			<DirectoryLayoutSelection
				clientId={clientId}
				attributes={attributes}
				setAttributes={setAttributes}
				onLayoutSelect={handleLayoutSelection}
			/>
		</div>
	);
}
