import { useBlockProps, RichText, InspectorControls, PanelColorSettings } from '@wordpress/block-editor';
import { PanelBody, TextControl, TextareaControl, ToggleControl, RangeControl, Notice, Tooltip, SelectControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
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 {
        heading,
        description,
        disclaimer,
        buttonText,
        buttonUrl,
        useShortcode,
        customShortcode,
        sectionBgColor,
        sectionPadding,
        headingColor,
        textColor,
        inputBgColor,
        btnBgColor,
        btnTextColor,
        btnHoverBgColor,
        btnHoverTextColor,
        blockId,
        signupStyle
    } = attributes;

    // Get Pro status from localized variable
    const isPro = window.awtVars?.isPro || false;

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

    // Conditional class rendering to avoid !important conflicts
    const isFun = signupStyle === 'fun';
    const isElegant = signupStyle === 'elegant';

    const containerClass = sectionBgColor || sectionPadding !== null
        ? '' // If user explicitly sets color/padding, rely on style prop (overrides defaults) -> But wait, elegant default bg is different.
        // We should set defaults based on style if no override.
        : (isElegant ? 'bg-gray-900 py-24' : 'bg-coral-pop py-24');

    const headingClass = headingColor
        ? (isElegant ? 'text-3xl md:text-4xl font-serif font-bold mb-4 text-center text-white' : 'text-4xl md:text-5xl font-black text-center mb-4')
        : (isElegant ? 'text-3xl md:text-4xl font-serif font-bold mb-4 text-center text-white' : 'section-heading');

    const descClass = textColor
        ? 'text-center text-lg mb-8 max-w-2xl mx-auto'
        : (isElegant
            ? 'text-center text-lg text-gray-300 max-w-2xl mx-auto mb-10 font-light'
            : 'text-center text-lg mb-8 text-white/90 max-w-2xl mx-auto');

    const disclaimerClass = textColor
        ? 'text-center text-sm mt-4'
        : (isElegant
            ? 'text-center text-xs mt-6 text-gray-500'
            : 'text-center text-sm text-white/70 mt-4');

    const inputClass = inputBgColor
        ? 'flex-1 px-6 py-4 rounded-full text-lg'
        : (isElegant
            ? 'flex-1 px-6 py-4 rounded bg-white/10 border border-white/20 text-white placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-white transition-all'
            : 'flex-1 px-6 py-4 rounded-full text-lg bg-white text-navy');

    const btnClass = btnBgColor
        ? 'btn-signup px-8 py-4 rounded-full font-bold text-lg transition-all duration-300'
        : (isElegant
            ? 'btn-signup px-8 py-4 rounded bg-white text-gray-900 font-bold hover:bg-gray-200 transition-colors flex-shrink-0'
            : 'btn-fun btn-yellow btn-signup px-8 py-4 rounded-full font-bold text-lg transition-all duration-300');

    // Dynamic hover styles
    const hoverStyles = `
        .block-${blockId} .btn-signup:hover {
            ${btnHoverBgColor ? `background-color: ${btnHoverBgColor} !important;` : ''}
            ${btnHoverTextColor ? `color: ${btnHoverTextColor} !important;` : ''}
        }
    `;

    const blockProps = useBlockProps({
        className: `alignfull block-${blockId} awt-child-author-signup ${containerClass}`,
        style: {
            backgroundColor: sectionBgColor || undefined, // If undefined, falls back to class default
            paddingTop: sectionPadding !== null ? `${sectionPadding}px` : undefined,
            paddingBottom: sectionPadding !== null ? `${sectionPadding}px` : undefined,
        }
    });

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

                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    <TextControl
                        label={__('Heading', 'author-website-templates')}
                        value={heading}
                        onChange={(value) => setAttributes({ heading: value })}
                        help={__('You can also edit directly on the canvas', 'author-website-templates')}
                    />

                    <TextareaControl
                        label={__('Description', 'author-website-templates')}
                        value={description}
                        onChange={(value) => setAttributes({ description: value })}
                        rows={3}
                        help={__('You can also edit directly on the canvas', 'author-website-templates')}
                    />

                    <TextareaControl
                        label={__('Disclaimer Text', 'author-website-templates')}
                        value={disclaimer}
                        onChange={(value) => setAttributes({ disclaimer: value })}
                        rows={2}
                    />

                    <hr style={{ margin: '16px 0' }} />

                    <h4 style={{ marginBottom: '12px', fontWeight: 'bold' }}>{__('Form Settings', 'author-website-templates')}</h4>

                    <ToggleControl
                        label={__('Use Custom Shortcode', 'author-website-templates')}
                        checked={useShortcode}
                        onChange={(value) => setAttributes({ useShortcode: value })}
                        help={__('Enable to use your own form plugin shortcode (e.g., Contact Form 7, WPForms)', 'author-website-templates')}
                    />

                    {useShortcode ? (
                        <TextareaControl
                            label={__('Paste Shortcode Here', 'author-website-templates')}
                            value={customShortcode}
                            onChange={(value) => setAttributes({ customShortcode: value })}
                            placeholder="[contact-form-7 id='123']"
                            rows={3}
                            help={__('Example: [contact-form-7 id="123"] or [wpforms id="456"]', 'author-website-templates')}
                        />
                    ) : (
                        <>
                            <TextControl
                                label={__('Button Text', 'author-website-templates')}
                                value={buttonText}
                                onChange={(value) => setAttributes({ buttonText: value })}
                            />
                            <TextControl
                                label={__('Button URL', 'author-website-templates')}
                                value={buttonUrl}
                                onChange={(value) => setAttributes({ buttonUrl: value })}
                                placeholder="#"
                                help={__('Where should the button link to?', 'author-website-templates')}
                            />
                        </>
                    )}
                </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={__('Section Colors', 'author-website-templates')}
                            colorSettings={[
                                {
                                    value: sectionBgColor,
                                    onChange: isPro ? (color) => setAttributes({ sectionBgColor: color }) : undefined,
                                    label: __('Section Background', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                                {
                                    value: headingColor,
                                    onChange: isPro ? (color) => setAttributes({ headingColor: color }) : undefined,
                                    label: __('Heading Color', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                                {
                                    value: textColor,
                                    onChange: isPro ? (color) => setAttributes({ textColor: color }) : undefined,
                                    label: __('Text Color', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                            ]}
                        />
                    </ProLock>

                    <ProLock isPro={isPro}>
                        <RangeControl
                            label={__('Section Padding (px)', 'author-website-templates')}
                            value={sectionPadding !== null ? sectionPadding : 96}
                            onChange={isPro ? (value) => setAttributes({ sectionPadding: value }) : undefined}
                            min={0}
                            max={200}
                            step={8}
                            disabled={!isPro}
                            help={isPro ? __('Default: 96px (py-24)', 'author-website-templates') : __('Pro feature', 'author-website-templates')}
                        />
                    </ProLock>

                    <ProLock isPro={isPro}>
                        <PanelColorSettings
                            title={__('Form Colors', 'author-website-templates')}
                            colorSettings={[
                                {
                                    value: inputBgColor,
                                    onChange: isPro ? (color) => setAttributes({ inputBgColor: color }) : undefined,
                                    label: __('Input Background', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                                {
                                    value: btnBgColor,
                                    onChange: isPro ? (color) => setAttributes({ btnBgColor: color }) : undefined,
                                    label: __('Button Background', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                                {
                                    value: btnTextColor,
                                    onChange: isPro ? (color) => setAttributes({ btnTextColor: color }) : undefined,
                                    label: __('Button Text', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                                {
                                    value: btnHoverBgColor,
                                    onChange: isPro ? (color) => setAttributes({ btnHoverBgColor: color }) : undefined,
                                    label: __('Button Hover Background', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                                {
                                    value: btnHoverTextColor,
                                    onChange: isPro ? (color) => setAttributes({ btnHoverTextColor: color }) : undefined,
                                    label: __('Button Hover Text', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                            ]}
                        />
                    </ProLock>
                </PanelBody>
            </InspectorControls>

            <section {...blockProps}>
                {/* Dynamic Hover Styles */}
                <style>{hoverStyles}</style>

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

                    <RichText
                        tagName="p"
                        className={descClass}
                        value={description}
                        onChange={(value) => setAttributes({ description: value })}
                        placeholder={__('Enter description...', 'author-website-templates')}
                        style={{ color: textColor || undefined }}
                    />

                    {/* Form Render Logic */}
                    {useShortcode ? (
                        <div className="shortcode-placeholder" style={{
                            background: 'rgba(255, 255, 255, 0.1)',
                            border: '2px dashed rgba(255, 255, 255, 0.3)',
                            padding: '40px',
                            borderRadius: '12px',
                            textAlign: 'center',
                            marginBottom: '20px'
                        }}>
                            {customShortcode ? (
                                <>
                                    <p style={{ color: '#fff', marginBottom: '10px', fontWeight: 'bold' }}>
                                        {__('📋 Shortcode Preview', 'author-website-templates')}
                                    </p>
                                    <code style={{
                                        background: 'rgba(0, 0, 0, 0.2)',
                                        padding: '10px 15px',
                                        borderRadius: '4px',
                                        color: '#fff',
                                        fontSize: '14px',
                                        display: 'inline-block'
                                    }}>
                                        {customShortcode}
                                    </code>
                                    <p style={{ color: 'rgba(255, 255, 255, 0.7)', marginTop: '10px', fontSize: '13px' }}>
                                        {__('This shortcode will render on the frontend', 'author-website-templates')}
                                    </p>
                                </>
                            ) : (
                                <p style={{ color: 'rgba(255, 255, 255, 0.7)' }}>
                                    {__('⚠️ Please paste your shortcode in the sidebar settings', 'author-website-templates')}
                                </p>
                            )}
                        </div>
                    ) : (
                        <div className="flex flex-col sm:flex-row gap-4 max-w-2xl mx-auto items-center">
                            <input
                                type="email"
                                placeholder="your.email@example.com"
                                className={inputClass}
                                style={{ backgroundColor: inputBgColor || undefined }}
                                disabled
                            />
                            <RichText
                                tagName="span"
                                value={buttonText}
                                onChange={(value) => setAttributes({ buttonText: value })}
                                placeholder={__('Button text...', 'author-website-templates')}
                                className={btnClass}
                                style={{
                                    backgroundColor: btnBgColor || undefined,
                                    color: btnTextColor || undefined,
                                }}
                            />
                        </div>
                    )}

                    <RichText
                        tagName="p"
                        className={disclaimerClass}
                        value={disclaimer}
                        onChange={(value) => setAttributes({ disclaimer: value })}
                        placeholder={__('Enter disclaimer...', 'author-website-templates')}
                        style={{ color: textColor || undefined }}
                    />
                </div>
            </section>
        </>
    );
}
