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

/**
 * ProLock Component - Wrapper for Pro-only controls
 * Renders children normally if Pro, otherwise shows locked/grayed controls with upgrade link
 */
const ProLock = ({ isPro, children }) => {
    if (isPro) return children;

    return (
        <div className="pro-lock-wrapper" style={{ position: 'relative', cursor: 'not-allowed' }}>
            {/* The actual controls (Blurred & Disabled) */}
            <div style={{ opacity: 0.4, pointerEvents: 'none', filter: 'grayscale(100%)' }}>
                {children}
            </div>

            {/* The Overlay (Clickable) */}
            <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">
                    {/* Invisible div to catch hover/click */}
                    <div style={{ width: '100%', height: '100%' }} />
                </Tooltip>
            </a>
        </div>
    );
};

export default function Edit({ attributes, setAttributes, clientId }) {
    const {
        blockId,
        heading,
        description,
        buttonText,
        formShortcode,
        sectionBgColor,
        textColor,
        buttonBgColor,
        buttonTextColor,
        sectionPadding
    } = attributes;

    const isPro = window.awtVars?.isPro || false;

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

    // Conditional Styles Logic: If custom color/padding set -> remove default class, apply inline style
    const containerClass = sectionBgColor ? '' : 'bg-white';

    const blockProps = useBlockProps({
        className: `alignfull block-${blockId} awt-child-author-contact ${containerClass}`,
        style: {
            backgroundColor: sectionBgColor || undefined,
            paddingTop: sectionPadding !== null ? `${sectionPadding}px` : undefined,
            paddingBottom: sectionPadding !== null ? `${sectionPadding}px` : undefined,
        }
    });

    const headingStyles = { color: textColor || undefined };
    const textStyles = { color: textColor || undefined };
    const buttonStyles = {
        backgroundColor: buttonBgColor || undefined,
        color: buttonTextColor || undefined,
        borderColor: buttonBgColor || undefined
    };

    const buttonClass = buttonBgColor ? 'btn-fun' : 'btn-fun bg-yellow-sun';
    const textClass = textColor ? '' : 'text-navy';

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Form Settings', 'author-website-templates')}>
                    <TextControl
                        label={__('Form Shortcode', 'author-website-templates')}
                        value={formShortcode}
                        onChange={(value) => setAttributes({ formShortcode: value })}
                        help={__('Enter a shortcode (e.g. [contact-form-7 ...]) to replace the default form.', 'author-website-templates')}
                    />
                </PanelBody>
            </InspectorControls>

            <InspectorControls group="styles">
                <PanelBody title={__('Dimensions', 'author-website-templates')} initialOpen={true}>
                    <ProLock isPro={isPro}>
                        <RangeControl
                            label={__('Section Padding (px)', 'author-website-templates')}
                            value={sectionPadding !== null ? sectionPadding : 96}
                            onChange={(value) => setAttributes({ sectionPadding: value })}
                            min={0}
                            max={200}
                            help={isPro ? __('Default: 96px (py-24)', 'author-website-templates') : __('Pro feature', 'author-website-templates')}
                        />
                    </ProLock>
                </PanelBody>

                <PanelColorSettings
                    title={__('Unused Title', 'author-website-templates')}
                    initialOpen={true}
                    colorSettings={[]}
                >
                    {/* 
                       Note: PanelColorSettings acts as a panel itself usually. 
                       But user asked to wrap contents in ProLock. 
                       PanelColorSettings doesn't accept children nicely if used as self-closing with colorSettings prop.
                       However, if we put ProLock around it, the whole panel is locked. That works.
                       Wait, the user said: "Use a single <PanelColorSettings> component inside the Styles tab to group all color options... The entire contents of the Styles Tab must be wrapped in the <ProLock> component." 
                       
                       So structure:
                       <InspectorControls group="styles">
                           <ProLock isPro={isPro}>
                               <PanelBody Dimensions>...</PanelBody>
                               <PanelColorSettings ... />
                           </ProLock>
                       </InspectorControls>
                       
                       This implies ONE ProLock wrapping everything.
                     */}
                </PanelColorSettings>
            </InspectorControls>

            {/* 
            Re-doing the InspectorControls part to correctly wrap everything in ProLock 
            and follow exact request.
            */}
            <InspectorControls group="styles">
                {!isPro && (
                    <PanelBody>
                        <Notice status="warning" isDismissible={false}>
                            {__('🔒 Upgrade to Pro to unlock styling controls', 'author-website-templates')}
                        </Notice>
                    </PanelBody>
                )}
                <ProLock isPro={isPro}>
                    <PanelBody title={__('Dimensions', 'author-website-templates')}>
                        <RangeControl
                            label={__('Section Padding (px)', 'author-website-templates')}
                            value={sectionPadding !== null ? sectionPadding : 96}
                            onChange={(value) => setAttributes({ sectionPadding: value })}
                            min={0}
                            max={200}
                        />
                    </PanelBody>

                    <PanelColorSettings
                        title={__('Colors', 'author-website-templates')}
                        initialOpen={true}
                        colorSettings={[
                            {
                                value: sectionBgColor,
                                onChange: (color) => setAttributes({ sectionBgColor: color }),
                                label: __('Section Background', 'author-website-templates'),
                            },
                            {
                                value: textColor,
                                onChange: (color) => setAttributes({ textColor: color }),
                                label: __('Text Color', 'author-website-templates'),
                            },
                            {
                                value: buttonBgColor,
                                onChange: (color) => setAttributes({ buttonBgColor: color }),
                                label: __('Button Background', 'author-website-templates'),
                            },
                            {
                                value: buttonTextColor,
                                onChange: (color) => setAttributes({ buttonTextColor: color }),
                                label: __('Button Text Color', 'author-website-templates'),
                            },
                        ]}
                    />
                </ProLock>
            </InspectorControls>

            <section {...blockProps}>
                <div className="awt-container container mx-auto px-6">
                    <RichText
                        tagName="h2"
                        className="section-heading"
                        value={heading}
                        onChange={(value) => setAttributes({ heading: value })}
                        placeholder={__('Heading...', 'author-website-templates')}
                        style={headingStyles}
                    />

                    <RichText
                        tagName="p"
                        className={`text-lg ${textClass}/80 text-center max-w-2xl mx-auto mb-12`}
                        value={description}
                        onChange={(value) => setAttributes({ description: value })}
                        placeholder={__('Description...', 'author-website-templates')}
                        style={{ ...textStyles, opacity: 0.8 }}
                    />

                    {formShortcode ? (
                        <div className="flex items-center justify-center p-12 border-2 border-dashed border-gray-300 rounded-lg bg-gray-50 text-gray-500">
                            <p>📧 {__('Shortcode Form will be rendered here:', 'author-website-templates')} <strong>{formShortcode}</strong></p>
                        </div>
                    ) : (
                        <form className="max-w-3xl mx-auto pointer-events-none">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                                <div>
                                    <label className={`block mb-2 font-bold ${textClass}`} style={textStyles}>Your Name</label>
                                    <input type="text" placeholder="Like 'Leo the Lion'"
                                        className="w-full p-4 rounded-lg bg-cream border-2 border-transparent text-navy placeholder:text-navy/50 focus:outline-none focus:ring-2 focus:ring-blue-sky transition-all"
                                        readOnly
                                    />
                                </div>
                                <div>
                                    <label className={`block mb-2 font-bold ${textClass}`} style={textStyles}>Your Email</label>
                                    <input type="email" placeholder="your-email@example.com"
                                        className="w-full p-4 rounded-lg bg-cream border-2 border-transparent text-navy placeholder:text-navy/50 focus:outline-none focus:ring-2 focus:ring-blue-sky transition-all"
                                        readOnly
                                    />
                                </div>
                            </div>

                            <div className="mb-6">
                                <label className={`block mb-2 font-bold ${textClass}`} style={textStyles}>What's this about?</label>
                                <select
                                    className="w-full p-4 rounded-lg bg-cream border-2 border-transparent text-navy focus:outline-none focus:ring-2 focus:ring-blue-sky transition-all appearance-none"
                                    readOnly
                                >
                                    <option>A School Visit</option>
                                    <option>A Question About a Book</option>
                                    <option>Sharing a Drawing!</option>
                                </select>
                            </div>

                            <div className="mb-8">
                                <label className={`block mb-2 font-bold ${textClass}`} style={textStyles}>Your Message</label>
                                <textarea rows="6" placeholder="Tell me all about it..."
                                    className="w-full p-4 rounded-lg bg-cream border-2 border-transparent text-navy placeholder:text-navy/50 focus:outline-none focus:ring-2 focus:ring-blue-sky transition-all"
                                    readOnly
                                ></textarea>
                            </div>

                            <div className="text-center">
                                <div className={`inline-block px-8 py-3 rounded-full font-extrabold font-sans uppercase tracking-wide text-navy shadow-lg transition-all duration-300 ease-in-out ${buttonClass}`} style={buttonStyles}>
                                    <RichText
                                        value={buttonText}
                                        onChange={(value) => setAttributes({ buttonText: value })}
                                        placeholder={__('Button Text...', 'author-website-templates')}
                                        tagName="span"
                                    />
                                </div>
                            </div>
                        </form>
                    )}
                </div>
            </section>
        </>
    );
}
