import { __ } from '@wordpress/i18n';
import { useBlockProps, RichText, InspectorControls, PanelColorSettings, MediaUpload, MediaUploadCheck } from '@wordpress/block-editor';
import { PanelBody, Button, ToggleControl, TextControl, TextareaControl, RangeControl, BaseControl, Tooltip, Notice, SelectControl } from '@wordpress/components';
import { useEffect } from '@wordpress/element';

const ProLock = ({ isPro, children }) => {
    if (isPro) return children;
    return (
        <div className="pro-lock-wrapper relative group cursor-not-allowed">
            <div className="opacity-40 pointer-events-none grayscale filter">{children}</div>
            <a href="https://rswpthemes.com/author-portfolio-pro-wordpress-theme/" target="_blank" rel="noopener noreferrer" className="absolute inset-0 z-10 cursor-pointer" aria-label="Upgrade to Pro">
                <Tooltip text="🔒 Pro Feature - Click to Upgrade"><div className="w-full h-full" /></Tooltip>
            </a>
        </div>
    );
};

export default function Edit({ attributes, setAttributes, clientId }) {
    const {
        blockId,
        eventStyle = 'fun', // Default to fun
        subHeading, heading, description,
        primaryBtnText, primaryBtnUrl,
        secondaryBtnText, secondaryBtnUrl,
        imageId, imageUrl,
        showDecorations,
        sectionBgColor, cardBgColor,
        subHeadingColor, headingColor, descColor,
        primaryBtnBg, primaryBtnTextColor, primaryBtnHoverBg, primaryBtnHoverText,
        secondaryBtnBg, secondaryBtnTextColor, secondaryBtnHoverBg, secondaryBtnHoverText,
        decoration1Color, decoration2Color, borderRadius
    } = attributes;

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

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

    const uniqueClass = `awt-events-cta-${blockId}`;

    const onSelectImage = (media) => {
        setAttributes({
            imageUrl: media.url,
            imageId: media.id
        });
    };

    // Generate Scoped CSS for Hover States
    const hoverCss = `
        .${uniqueClass} .btn-primary:hover {
            background-color: ${primaryBtnHoverBg} !important;
            color: ${primaryBtnHoverText} !important;
        }
        .${uniqueClass} .btn-secondary:hover {
            background-color: ${secondaryBtnHoverBg} !important;
            color: ${secondaryBtnHoverText} !important;
        }
    `;

    const blockProps = useBlockProps({
        className: `awt-child-author-events-cta ${uniqueClass} py-24`,
        style: { backgroundColor: sectionBgColor }
    });

    // Determine styles based on eventStyle
    const isFun = eventStyle === 'fun';
    const isElegant = eventStyle === 'elegant';

    // Container Classes
    const containerClasses = isFun
        ? "p-8 md:p-16 text-center md:text-left relative overflow-hidden shadow-2xl transition-all duration-300"
        : "p-8 md:p-16 text-center md:text-left bg-gray-800 rounded-xl shadow-2xl border border-gray-700 relative overflow-hidden";

    // Text Styles
    const subHeadingClasses = isFun
        ? "font-bold uppercase tracking-wider mb-2 block"
        : "text-gray-400 font-bold uppercase tracking-widest text-xs mb-4 block";

    // Force gray-400 for sub-heading in Elegant mode if no custom color is set
    const subHeadingStyle = isElegant && !subHeadingColor ? { color: '#9ca3af' } : { color: subHeadingColor };

    const headingClasses = isFun
        ? "text-3xl md:text-5xl font-black mb-6"
        : "text-3xl md:text-5xl font-serif font-bold text-white mb-6";

    const descClasses = isFun
        ? "text-lg mb-8 leading-relaxed"
        : "text-lg text-gray-300 mb-8 leading-relaxed";

    // Button Classes
    const primaryBtnClasses = isFun
        ? "btn-fun btn-primary inline-block cursor-pointer text-center"
        : "px-8 py-3 rounded font-medium bg-white text-gray-900 hover:bg-gray-200 transition-colors inline-block cursor-pointer text-center";

    const secondaryBtnClasses = isFun
        ? "btn-fun btn-secondary bg-transparent border-2 border-white inline-block cursor-pointer text-center"
        : "px-8 py-3 rounded font-medium border border-gray-500 text-white hover:bg-gray-700 transition-colors inline-block cursor-pointer text-center";

    // Image Classes
    const imageWrapperClasses = isFun
        ? "hidden md:block" // Direct wrapper for Fun mode is just hidden/block
        : "hidden md:block w-full max-w-sm aspect-square bg-gray-700 rounded-lg overflow-hidden shadow-lg mx-auto"; // Elegant mode wrapper

    const imageClasses = isFun
        ? "rounded-xl shadow-lg transform rotate-3 border-4 border-white/20 transition-opacity"
        : "object-cover w-full h-full";

    return (
        <>
            <style>{hoverCss}</style>

            <InspectorControls>
                <PanelBody title={__('Text Content', 'author-website-templates')}>
                    <SelectControl
                        label={__('Block Style', 'author-website-templates')}
                        value={eventStyle}
                        options={[
                            { label: 'Fun (Child)', value: 'fun' },
                            { label: 'Elegant (Author)', value: 'elegant' },
                        ]}
                        onChange={(value) => setAttributes({ eventStyle: value })}
                    />
                    <TextControl
                        label={__('Sub Heading', 'author-website-templates')}
                        value={subHeading}
                        onChange={(value) => setAttributes({ subHeading: value })}
                    />
                    <TextControl
                        label={__('Main 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={4}
                    />
                </PanelBody>

                <PanelBody title={__('Buttons', 'author-website-templates')} initialOpen={false}>
                    <p className="font-bold mb-2">{__('Primary Button', 'author-website-templates')}</p>
                    <TextControl
                        label="Label"
                        value={primaryBtnText}
                        onChange={(value) => setAttributes({ primaryBtnText: value })}
                    />
                    <TextControl
                        label="URL"
                        value={primaryBtnUrl}
                        onChange={(value) => setAttributes({ primaryBtnUrl: value })}
                    />
                    <hr className="my-4" />
                    <p className="font-bold mb-2">{__('Secondary Button', 'author-website-templates')}</p>
                    <TextControl
                        label="Label"
                        value={secondaryBtnText}
                        onChange={(value) => setAttributes({ secondaryBtnText: value })}
                    />
                    <TextControl
                        label="URL"
                        value={secondaryBtnUrl}
                        onChange={(value) => setAttributes({ secondaryBtnUrl: value })}
                    />
                </PanelBody>

                <PanelBody title={__('Image', 'author-website-templates')} initialOpen={false}>
                    <MediaUploadCheck>
                        <MediaUpload
                            onSelect={onSelectImage}
                            allowedTypes={['image']}
                            value={imageId}
                            render={({ open }) => (
                                <BaseControl label={__('Right Image', 'author-website-templates')}>
                                    <Button isSecondary onClick={open} className="w-full">
                                        {imageUrl ? __('Replace Image', 'author-website-templates') : __('Select Image', 'author-website-templates')}
                                    </Button>
                                    {imageUrl && (
                                        <div className="mt-2">
                                            <img src={imageUrl} alt="Preview" className="w-full h-auto rounded shadow-sm" style={{ maxHeight: '150px', objectFit: 'cover' }} />
                                            <Button isDestructive isLink onClick={() => setAttributes({ imageUrl: '', imageId: 0 })} className="mt-2 text-xs">
                                                {__('Remove Image', 'author-website-templates')}
                                            </Button>
                                        </div>
                                    )}
                                </BaseControl>
                            )}
                        />
                    </MediaUploadCheck>
                </PanelBody>
            </InspectorControls>

            <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={__('Container', 'author-website-templates')}>
                        <RangeControl
                            label={__('Border Radius', 'author-website-templates')}
                            value={borderRadius}
                            onChange={(value) => setAttributes({ borderRadius: value })}
                            min={0}
                            max={60}
                        />
                        <PanelColorSettings
                            title={__('Background Colors', 'author-website-templates')}
                            initialOpen={true}
                            colorSettings={[
                                { value: sectionBgColor, onChange: (c) => setAttributes({ sectionBgColor: c }), label: __('Section Background') },
                                { value: cardBgColor, onChange: (c) => setAttributes({ cardBgColor: c }), label: __('Card (Inner) Background') },
                            ]}
                        />
                    </PanelBody>

                    <PanelColorSettings
                        title={__('Typography Colors', 'author-website-templates')}
                        initialOpen={false}
                        colorSettings={[
                            { value: subHeadingColor, onChange: (c) => setAttributes({ subHeadingColor: c }), label: __('Sub Heading') },
                            { value: headingColor, onChange: (c) => setAttributes({ headingColor: c }), label: __('Heading') },
                            { value: descColor, onChange: (c) => setAttributes({ descColor: c }), label: __('Description') },
                        ]}
                    />

                    <PanelBody title={__('Decorations', 'author-website-templates')} initialOpen={false}>
                        <ToggleControl
                            label={__('Show Decorations', 'author-website-templates')}
                            checked={showDecorations}
                            onChange={(value) => setAttributes({ showDecorations: value })}
                            help={!isFun ? __('Decorations are only available in "Fun" style.', 'author-website-templates') : ''}
                            disabled={!isFun}
                        />
                        {showDecorations && isFun && (
                            <PanelColorSettings
                                title={__('Decoration Colors', 'author-website-templates')}
                                initialOpen={true}
                                colorSettings={[
                                    { value: decoration1Color, onChange: (c) => setAttributes({ decoration1Color: c }), label: __('Circle 1 (Top Right)') },
                                    { value: decoration2Color, onChange: (c) => setAttributes({ decoration2Color: c }), label: __('Circle 2 (Bottom Left)') },
                                ]}
                            />
                        )}
                    </PanelBody>

                    <PanelColorSettings
                        title={__('Primary Button Styles', 'author-website-templates')}
                        initialOpen={false}
                        colorSettings={[
                            { value: primaryBtnBg, onChange: (c) => setAttributes({ primaryBtnBg: c }), label: __('Background (Normal)') },
                            { value: primaryBtnTextColor, onChange: (c) => setAttributes({ primaryBtnTextColor: c }), label: __('Text (Normal)') },
                            { value: primaryBtnHoverBg, onChange: (c) => setAttributes({ primaryBtnHoverBg: c }), label: __('Background (Hover)') },
                            { value: primaryBtnHoverText, onChange: (c) => setAttributes({ primaryBtnHoverText: c }), label: __('Text (Hover)') },
                        ]}
                    />

                    <PanelColorSettings
                        title={__('Secondary Button Styles', 'author-website-templates')}
                        initialOpen={false}
                        colorSettings={[
                            { value: secondaryBtnBg, onChange: (c) => setAttributes({ secondaryBtnBg: c }), label: __('Background (Normal)') },
                            { value: secondaryBtnTextColor, onChange: (c) => setAttributes({ secondaryBtnTextColor: c }), label: __('Text (Normal)') },
                            { value: secondaryBtnHoverBg, onChange: (c) => setAttributes({ secondaryBtnHoverBg: c }), label: __('Background (Hover)') },
                            { value: secondaryBtnHoverText, onChange: (c) => setAttributes({ secondaryBtnHoverText: c }), label: __('Text (Hover)') },
                        ]}
                    />
                </ProLock>
            </InspectorControls>

            <div {...blockProps}>
                <div className="awt-container mx-auto px-6">
                    <div
                        className={containerClasses}
                        style={{
                            backgroundColor: cardBgColor,
                            borderRadius: `${borderRadius}px`
                        }}
                    >
                        {showDecorations && isFun && (
                            <>
                                <div
                                    className="absolute top-0 right-0 w-64 h-64 bg-white/5 rounded-full -mr-16 -mt-16 pointer-events-none"
                                    style={decoration1Color ? { backgroundColor: decoration1Color, opacity: 0.05 } : {}}
                                ></div>
                                <div
                                    className="absolute bottom-0 left-0 w-40 h-40 bg-yellow-sun/10 rounded-full -ml-10 -mb-10 pointer-events-none"
                                    style={decoration2Color ? { backgroundColor: decoration2Color, opacity: 0.1 } : {}}
                                ></div>
                            </>
                        )}

                        <div className="relative z-10 grid md:grid-cols-2 gap-12 items-center">
                            <div>
                                <RichText
                                    tagName="span"
                                    className={subHeadingClasses}
                                    value={subHeading}
                                    onChange={(value) => setAttributes({ subHeading: value })}
                                    style={subHeadingStyle}
                                    placeholder={__('Sub Heading...', 'author-website-templates')}
                                />
                                <RichText
                                    tagName="h2"
                                    className={headingClasses}
                                    value={heading}
                                    onChange={(value) => setAttributes({ heading: value })}
                                    style={{ color: headingColor }}
                                    placeholder={__('Main Heading...', 'author-website-templates')}
                                />
                                <RichText
                                    tagName="p"
                                    className={descClasses}
                                    value={description}
                                    onChange={(value) => setAttributes({ description: value })}
                                    style={{ color: descColor }}
                                    placeholder={__('Description...', 'author-website-templates')}
                                />
                                <div className="flex flex-col sm:flex-row gap-4 justify-center md:justify-start">
                                    <span
                                        className={primaryBtnClasses}
                                        style={{ backgroundColor: primaryBtnBg, color: primaryBtnTextColor }}
                                    >
                                        {primaryBtnText}
                                    </span>
                                    <span
                                        className={secondaryBtnClasses}
                                        style={{
                                            backgroundColor: secondaryBtnBg,
                                            color: secondaryBtnTextColor,
                                            borderColor: secondaryBtnTextColor || (isElegant ? '#6b7280' : 'white') // Default border color fallback
                                        }}
                                    >
                                        {secondaryBtnText}
                                    </span>
                                </div>
                            </div>
                            <div className={imageWrapperClasses}>
                                {!imageUrl ? (
                                    <div className={`rounded-xl shadow-lg border-4 border-white/20 bg-black/20 h-64 w-full flex items-center justify-center text-white ${isElegant ? 'border-0' : ''}`}>
                                        {__('Select Image in Inspector', 'author-website-templates')}
                                    </div>
                                ) : (
                                    <img
                                        src={imageUrl}
                                        alt="Event"
                                        className={imageClasses}
                                    />
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}
