import { useBlockProps, useInnerBlocksProps, RichText, InspectorControls, PanelColorSettings } from '@wordpress/block-editor';
import { PanelBody, Notice, Tooltip, SelectControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useEffect } from '@wordpress/element';

// ProLock Component
const ProLock = ({ isPro, children }) => {
    if (isPro) return children;
    return (
        <div className="pro-lock-wrapper" style={{ position: 'relative', cursor: 'not-allowed' }}>
            <div style={{ opacity: 0.4, pointerEvents: 'none', filter: 'grayscale(100%)' }}>{children}</div>
            <a href="https://rswpthemes.com/author-portfolio-pro-wordpress-theme/" target="_blank" rel="noopener noreferrer" style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', zIndex: 10, cursor: 'pointer' }} aria-label="Upgrade to Pro">
                <Tooltip text="🔒 Pro Feature - Click to Upgrade"><div style={{ width: '100%', height: '100%' }} /></Tooltip>
            </a>
        </div>
    );
};

// Default Template (4 Fun Facts)
const TEMPLATE = [
    ['awt/child-author-fact-card', { icon: '🎨', text: 'My favorite color is rainbow!' }],
    ['awt/child-author-fact-card', { icon: '🍕', text: 'I love pizza with extra cheese!' }],
    ['awt/child-author-fact-card', { icon: '🐶', text: 'I have a dog named Buddy!' }],
    ['awt/child-author-fact-card', { icon: '📚', text: 'I read 20 books this year!' }],
];

export default function Edit({ attributes, setAttributes, clientId }) {
    const { heading, sectionBgColor, headingColor, blockId, factsStyle } = attributes;
    const isPro = window.awtVars?.isPro || false;

    useEffect(() => {
        if (!blockId) setAttributes({ blockId: clientId });
    }, [blockId, clientId, setAttributes]);

    const isFun = factsStyle === 'fun' || !factsStyle;

    const containerBaseClass = isFun ? 'bg-coral-pop' : 'text-white';
    const containerClass = sectionBgColor ? `py-24 text-white` : `py-24 ${containerBaseClass} text-white`;

    const headingBaseClass = isFun
        ? 'text-4xl md:text-5xl font-black text-center mb-12'
        : 'text-3xl md:text-4xl font-serif font-bold text-center mb-16';
    const headingClass = headingColor ? headingBaseClass : headingBaseClass;

    const gridClass = isFun
        ? 'grid grid-cols-1 md:grid-cols-2 gap-8 text-xl font-bold'
        : 'grid grid-cols-1 md:grid-cols-2 gap-6';

    const maxWidthClass = isFun ? 'max-w-4xl' : 'max-w-5xl';

    const blockProps = useBlockProps({
        className: `block-${blockId} ${containerClass}`,
        style: {
            backgroundColor: sectionBgColor || (isFun ? undefined : '#1e293b'),
        }
    });

    const innerBlocksProps = useInnerBlocksProps(
        { className: gridClass },
        {
            allowedBlocks: ['awt/child-author-fact-card'],
            template: TEMPLATE,
        }
    );

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Style Settings', 'author-website-templates')} initialOpen={true}>
                    <SelectControl
                        label={__('Block Style', 'author-website-templates')}
                        value={factsStyle}
                        options={[
                            { label: __('Fun (Child)', 'author-website-templates'), value: 'fun' },
                            { label: __('Elegant (Author)', 'author-website-templates'), value: 'elegant' },
                        ]}
                        onChange={(value) => setAttributes({ factsStyle: value })}
                    />
                </PanelBody>

                <PanelBody title={__('Design Settings', 'author-website-templates')} initialOpen={false}>
                    {!isPro && (
                        <Notice status="warning" isDismissible={false}>
                            {__('🔒 Upgrade to Pro to unlock styling controls', 'author-website-templates')}
                        </Notice>
                    )}

                    <ProLock isPro={isPro}>
                        <PanelColorSettings
                            title={__('Colors', 'author-website-templates')}
                            colorSettings={[
                                {
                                    value: sectionBgColor,
                                    onChange: (color) => setAttributes({ sectionBgColor: color }),
                                    label: __('Section Background', 'author-website-templates'),
                                },
                                {
                                    value: headingColor,
                                    onChange: (color) => setAttributes({ headingColor: color }),
                                    label: __('Heading Color', 'author-website-templates'),
                                },
                            ]}
                        />
                    </ProLock>
                </PanelBody>
            </InspectorControls>

            <section {...blockProps}>
                <div className={`awt-container ${maxWidthClass} mx-auto px-6`}>
                    <RichText
                        tagName="h2"
                        className={headingClass}
                        value={heading}
                        onChange={(v) => setAttributes({ heading: v })}
                        placeholder={__('Section heading...', 'author-website-templates')}
                        style={{ color: headingColor || undefined }}
                    />

                    <div {...innerBlocksProps} />
                </div>
            </section>
        </>
    );
}
