import { useBlockProps, RichText, InspectorControls, PanelColorSettings } from '@wordpress/block-editor';
import { PanelBody, TextControl, TextareaControl, ToggleControl, Notice, Tooltip } 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,
        placeholderText,
        useShortcode,
        customShortcode,
        sectionBgColor,
        headingColor,
        textColor,
        inputBgColor,
        btnBgColor,
        btnTextColor,
        btnHoverBgColor,
        btnHoverTextColor,
        blockId
    } = 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]);

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

    const blockProps = useBlockProps({
        className: `alignfull block-${blockId} py-24 ${sectionBgColor ? '' : 'bg-accent'} ${sectionBgColor ? '' : 'text-white'}`,
        style: {
            backgroundColor: sectionBgColor || undefined,
        }
    });

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    <TextControl
                        label={__('Heading', 'author-website-templates')}
                        value={heading}
                        onChange={(value) => setAttributes({ heading: value })}
                    />
                    <TextareaControl
                        label={__('Description', 'author-website-templates')}
                        value={description}
                        onChange={(value) => setAttributes({ description: value })}
                        rows={3}
                    />
                    <TextareaControl
                        label={__('Disclaimer', 'author-website-templates')}
                        value={disclaimer}
                        onChange={(value) => setAttributes({ disclaimer: value })}
                        rows={2}
                    />

                    <hr className="my-4" />

                    <h4 className="font-bold mb-2">{__('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}
                        />
                    ) : (
                        <>
                            <TextControl
                                label={__('Placeholder Text', 'author-website-templates')}
                                value={placeholderText}
                                onChange={(value) => setAttributes({ placeholderText: value })}
                            />
                            <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 })}
                            />
                        </>
                    )}
                </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,
                                },
                            ]}
                        />
                        <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}>
                <style>{hoverStyles}</style>
                <div className="max-w-2xl mx-auto px-6 text-center">
                    <svg className="text-4xl mx-auto text-white w-12 h-12 opacity-80" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><path d="M568.4 37.7C578.2 34.2 589 36.7 596.4 44C603.8 51.3 606.2 62.2 602.7 72L424.7 568.9C419.7 582.8 406.6 592 391.9 592C377.7 592 364.9 583.4 359.6 570.3L295.4 412.3C290.9 401.3 292.9 388.7 300.6 379.7L395.1 267.3C400.2 261.2 399.8 252.3 394.2 246.7C388.6 241.1 379.6 240.7 373.6 245.8L261.2 340.1C252.1 347.7 239.6 349.7 228.6 345.3L70.1 280.8C57 275.5 48.4 262.7 48.4 248.5C48.4 233.8 57.6 220.7 71.5 215.7L568.4 37.7z" /></svg>

                    <RichText
                        tagName="h2"
                        className="text-3xl font-serif font-bold mb-4"
                        value={heading}
                        onChange={(value) => setAttributes({ heading: value })}
                        style={{ color: headingColor || undefined }}
                    />

                    <RichText
                        tagName="p"
                        className={`mb-8 text-lg ${textColor ? '' : 'text-orange-100'}`}
                        value={description}
                        onChange={(value) => setAttributes({ description: value })}
                        style={{ color: textColor || undefined }}
                    />

                    {useShortcode ? (
                        <div className="bg-white/10 border-2 border-dashed border-white/30 p-8 rounded-lg text-center mb-4">
                            {customShortcode ? (
                                <code className="bg-black/20 px-3 py-2 rounded text-sm block mb-2">{customShortcode}</code>
                            ) : (
                                <p className="opacity-70 text-sm">Paste your shortcode in the sidebar settings</p>
                            )}
                            <p className="opacity-50 text-xs">Shortcode will be rendered on the frontend</p>
                        </div>
                    ) : (
                        <div className="flex flex-col sm:flex-row gap-3">
                            <input
                                type="email"
                                placeholder={placeholderText}
                                className="w-full px-6 py-4 rounded-lg text-primary focus:outline-none focus:ring-4 focus:ring-orange-400"
                                style={{ backgroundColor: inputBgColor || undefined }}
                                disabled
                            />
                            <button
                                className="px-8 py-4 bg-primary text-white font-bold rounded-lg hover:bg-gray-900 transition whitespace-nowrap"
                                style={{
                                    backgroundColor: btnBgColor || undefined,
                                    color: btnTextColor || undefined
                                }}
                            >
                                {buttonText}
                            </button>
                        </div>
                    )}

                    <RichText
                        tagName="p"
                        className={`text-xs mt-4 ${textColor ? '' : 'text-orange-200'}`}
                        value={disclaimer}
                        onChange={(value) => setAttributes({ disclaimer: value })}
                        style={{ color: textColor || undefined }}
                    />
                </div>
            </section>
        </>
    );
}
