import { __ } from '@wordpress/i18n';
import { useBlockProps, InnerBlocks, InspectorControls, BlockEditor } from '@wordpress/block-editor';
import {addFilter} from '@wordpress/hooks';
import { ToggleControl } from '@wordpress/components';
import { useEffect, useState } from '@wordpress/element';
import { createBlock } from '@wordpress/blocks'; // Used for creating new blocks
import { useSelect, subscribe } from '@wordpress/data'; // Import subscribe
import { Modal, Button } from '@wordpress/components'; // Import Modal for popup
import './editor.scss';

export default function Edit({ attributes, setAttributes, clientId }) {
    const { hasSidecontent, headerContainerStickyType } = attributes;

    // Popup visibility state
    const [isPopupVisible, setIsPopupVisible] = useState(false);
    const [hasIgnoredPopup, setHasIgnoredPopup] = useState(false); // Track if user has ignored the popup
    const [blockAdded, setBlockAdded] = useState(false); // Track whether a block has been added
    const [addedBlock, setAddedBlock] = useState(null); // Track the block that was added outside of viewport

    // Block props with custom className management
    const blockProps = useBlockProps({
        className: hasSidecontent ? 'has-sidecontent' : '', // Custom class
    });

    // Custom template logic based on hasSidecontent
    const template = [
        hasSidecontent ? ['lcp/sidecontent'] : null, // Only include 'lcp/sidecontent' if `hasSidecontent` is true
        ['lcp/header-container'],  // Add initial content to header-container
        ['lcp/main-area'], // Always include 'lcp/main-area'
        ['lcp/footer-container'] // Always include 'lcp/footer-container'
    ].filter(Boolean); // Remove any null or undefined values from the array
    
    // Render appender logic to handle block insertion
    const renderAppender = () => {
        return <InnerBlocks.ButtonBlockAppender />; // The default block appender
    };

    // Add sidecontent if attribute changes
    useEffect(() => {
        if (hasSidecontent) {
            // Create a new block and insert it in the block's inner blocks
            const blockToAdd = createBlock('lcp/sidecontent', {});
            wp.data.dispatch('core/block-editor').insertBlocks(blockToAdd, 1, clientId); // Insert at position 0
        }
    }, [hasSidecontent, clientId]); // Only runs when `hasSidecontent` or `clientId` changes


    // Reset the "Ignore" state when a new block is added (for the next block addition)


    // Use useSelect to subscribe to the state of inner blocks
    const innerBlocks = useSelect((select) => {
        return select('core/block-editor').getBlocks(clientId);
    }, [clientId]);

    // useEffect to handle sticky header
    useEffect(() => {
        const headerBlock = innerBlocks.find((block) => block.name === 'lcp/header-container');
        const sidecontentBlock = innerBlocks.find((block) => block.name === 'lcp/header-sidecontent');
        // Check if the block is found and the 'sticky' attribute has changed
        if (headerBlock && headerBlock.attributes && headerBlock.attributes.sticky !== undefined) {
            // Update the state with the new sticky value
            setAttributes({ headerContainerStickyType: headerBlock.attributes.sticky });
        }
        // Check if there is already a sidecontent block and remove it if so
        if (sidecontentBlock) {

        }
    }, [innerBlocks, clientId, setAttributes]); // Trigger the effect whenever the blocks change
    


    return (
        <div {...blockProps}>
            {/* Inspector Controls: Add a toggle for the `hasSidecontent` attribute */}
            <InspectorControls>
                <ToggleControl
                    label={__('Include Side Content', 'lcp-viewport')}
                    checked={hasSidecontent}
                    onChange={(value) => setAttributes({ hasSidecontent: value })}
                />
            </InspectorControls>

            <div id="lcp-viewport-outer">
                <div id="lcp-viewport-inner">
                    {/* Render the InnerBlocks with conditional template */}
                    <InnerBlocks
                        renderAppender={renderAppender} // Custom appender logic
                        template={template} // Dynamic template based on `hasSidecontent`
                    />
                </div>
            </div>

            {/* Modal for Popup */}
            {isPopupVisible && !hasIgnoredPopup && (
                <Modal
                    title={__('Block Outside Viewport', 'lcp-viewport')}
                    onRequestClose={closePopup} // Close on clicking outside
                    className="block-outside-popup"
                >
                    <p>{__('You added a block outside of the lcp/viewport container. Please make sure the block is inside the appropriate area.', 'lcp-viewport')}</p>
                    <Button isPrimary onClick={closePopup}>{__('Close', 'lcp-viewport')}</Button>
                    <Button isSecondary onClick={ignorePopup}>{__('Ignore', 'lcp-viewport')}</Button>
                </Modal>
            )}
        </div>
    );
}
