import { __ } from '@wordpress/i18n';
import {
    __experimentalHeading as Heading,
    __experimentalText as Text,
    Button,
    Card,
    CardBody,
    CardMedia,
} from '@wordpress/components';
import { useBlockProps } from '@wordpress/block-editor';
import { useDispatch } from '@wordpress/data';
import { createBlocksFromInnerBlocksTemplate } from '@wordpress/blocks';

// Helper function to convert camelCase to kebab-case for image names
const getImageName = (patternName) => {
    const imageMap = {
        'roundGrids': 'round-grids',
        'squareGrids': 'square-grids',
        'sidecards': 'sidecards',
        'wideSidecards': 'wide-sidecards'
    };
    return imageMap[patternName] || patternName;
};

/**
 * Internal dependencies
 */
import { getLayoutOptions } from '../templates';

// Layout patterns configuration - now centralized from variations
const LAYOUT_PATTERNS = getLayoutOptions();

// Directory Layout Selection Component
const DirectoryLayoutSelection = ({
    clientId,
    attributes,
    setAttributes,
    onBack,
    onLayoutSelect
}) => {
    const blockProps = useBlockProps({
        className: 'wpuf-p-8'
    });

    // Handle layout selection
    const handleLayoutSelection = (layoutName, template) => {
        if (onLayoutSelect) {
            // Use the parent's layout selection handler which includes confirmation
            onLayoutSelect(layoutName, template);
        }
    };

    return (
        <div {...blockProps}>
            {/* Back Button */}
            <div className="wpuf-mb-6">
                <Button
                    variant="secondary"
                    onClick={() => {
                        if (onBack) {
                            onBack();
                        }
                    }}
                    className="wpuf-back-to-layout-btn"
                >
                    <svg className="wpuf-w-4 wpuf-h-4 wpuf-mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 19l-7-7 7-7" />
                    </svg>
                    {__('Back to Current Layout', 'wpuf-pro')}
                </Button>
            </div>

            <div className="wpuf-text-center wpuf-mb-8">
                <Heading level={2} className="wpuf-text-2xl wpuf-font-semibold wpuf-mb-2">
                    {__('Choose a layout for your user directory', 'wpuf-pro')}
                </Heading>
                <Text className="wpuf-text-gray-600">
                    {__('Select a pre-designed layout or start with a blank canvas to create your own.', 'wpuf-pro')}
                </Text>
            </div>

            <div className="wpuf-grid wpuf-grid-cols-1 md:wpuf-grid-cols-3 wpuf-gap-6">
                {LAYOUT_PATTERNS.map((pattern) => (
                    <Card
                        key={pattern.name}
                        className="wpuf-cursor-pointer wpuf-transition-all wpuf-duration-300 wpuf-ease-in-out hover:wpuf-shadow-lg hover:wpuf-scale-105 wpuf-border wpuf-border-gray-200 hover:wpuf-border-blue-300"
                        onClick={() => handleLayoutSelection(pattern.name, pattern.template)}
                    >
                        <CardMedia className="wpuf-aspect-video wpuf-bg-gray-50 wpuf-flex wpuf-items-center wpuf-justify-center">
                            <img
                                alt={pattern.name}
                                src={(window.wpufUserDirectory?.asset_url || '') + '/images/' + getImageName(pattern.name) + '.png'}
                                className="wpuf-w-full wpuf-h-full wpuf-object-cover"
                                onError={(e) => {
                                    // Fallback to placeholder if image doesn't exist
                                    e.target.style.display = 'none';
                                    const placeholder = document.createElement('div');
                                    placeholder.className = 'wpuf-w-full wpuf-h-full wpuf-flex wpuf-items-center wpuf-justify-center wpuf-text-gray-400 wpuf-text-4xl';
                                    placeholder.innerHTML = '👥';
                                    e.target.parentNode.appendChild(placeholder);
                                }}
                            />
                        </CardMedia>
                        <CardBody className="wpuf-p-4">
                            <Heading level={3} className="wpuf-text-lg wpuf-font-medium wpuf-mb-2">
                                {pattern.title}
                            </Heading>
                        </CardBody>
                    </Card>
                ))}
            </div>
        </div>
    );
};

export default DirectoryLayoutSelection;
