import { useBlockProps, useInnerBlocksProps, RichText, InspectorControls, PanelColorSettings } from '@wordpress/block-editor';
import { PanelBody, TextareaControl, Notice, Tooltip, SelectControl, ToggleControl, RangeControl } 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 with 3 social icons
const TEMPLATE = [
    ['awt/child-author-social-icon', { platform: 'instagram', url: 'https://instagram.com/yourusername' }],
    ['awt/child-author-social-icon', { platform: 'facebook', url: 'https://facebook.com/yourusername' }],
    ['awt/child-author-social-icon', { platform: 'twitter', url: 'https://twitter.com/yourusername' }],
];

export default function Edit({ attributes, setAttributes, clientId }) {
    const { heading, description, sectionBgColor, curveColor, headingColor, textColor, blockId, socialsStyle, iconColor, hideCurve, sectionPadding } = attributes;
    const isPro = window.awtVars?.isPro || false;

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

    // Styles Configuration
    const isElegant = socialsStyle === 'elegant';

    // Container Logic
    // Background: If custom color is set, use inline style (empty class). Else use default theme class.
    const bgClass = sectionBgColor ? '' : (isElegant ? 'bg-[#f8fafc]' : 'bg-yellow-sun/20');
    // Border: Always apply border for Elegant style unless we need to clear it? User requested structural border to remain.
    const borderClass = isElegant ? 'border-t border-gray-100' : '';

    // Heading Logic
    const headingBase = isElegant
        ? 'text-3xl md:text-5xl font-serif font-bold text-center mb-6'
        : 'text-4xl md:text-5xl font-black text-center mb-4';
    // Color: If set, empty. Else default.
    const headingColorClass = headingColor ? '' : (isElegant ? 'text-slate-800' : 'text-navy');
    const finalHeadingClass = `${headingBase} ${headingColorClass}`;

    // Description Logic
    const descBase = isElegant
        ? 'text-xl max-w-lg mx-auto text-center mb-10 font-light'
        : 'text-xl max-w-lg mx-auto text-center mb-10';
    const descColorClass = textColor ? '' : (isElegant ? 'text-slate-500' : 'text-navy/80');
    const descClass = `${descBase} ${descColorClass}`;

    // Computed Styles
    const containerStyle = {
        backgroundColor: sectionBgColor || undefined,
        paddingTop: sectionPadding ? `${sectionPadding}px` : (isElegant ? '80px' : '96px'),
        paddingBottom: sectionPadding ? `${sectionPadding}px` : (isElegant ? '80px' : '96px'),
    };

    const blockProps = useBlockProps({
        className: `alignfull block-${blockId} relative ${bgClass} ${borderClass}`,
        style: containerStyle
    });

    const innerBlocksProps = useInnerBlocksProps(
        { className: 'flex space-x-8 justify-center flex-wrap gap-y-4' },
        {
            allowedBlocks: ['awt/child-author-social-icon'],
            template: TEMPLATE,
        }
    );

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    <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')}
                    />
                </PanelBody>

                <PanelBody title={__('Styles', 'author-website-templates')} initialOpen={true}>
                    <SelectControl
                        label={__('Block Style', 'author-website-templates')}
                        value={socialsStyle}
                        options={[
                            { label: __('Fun & Playful', 'author-website-templates'), value: 'fun' },
                            { label: __('Elegant & Minimal', 'author-website-templates'), value: 'elegant' },
                        ]}
                        onChange={(value) => setAttributes({ socialsStyle: 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}>
                        <ToggleControl
                            label={__('Hide Top Curve', 'author-website-templates')}
                            checked={hideCurve}
                            onChange={(value) => setAttributes({ hideCurve: value })}
                        />
                        <RangeControl
                            label={__('Section Padding', 'author-website-templates')}
                            value={sectionPadding}
                            onChange={(value) => setAttributes({ sectionPadding: value })}
                            min={0}
                            max={200}
                        />

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

            <section {...blockProps}>
                {/* Top SVG Wave */}
                {/* Top SVG Wave - Force hide if Elegant style, otherwise respect hideCurve toggle */}
                {(!isElegant && !hideCurve) && (
                    <div className="absolute top-0 left-0 w-full">
                        <svg viewBox="0 0 1440 100" fill="none" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" className="w-full h-auto">
                            <path d="M0 0H1440V100C1192.5 50.503 919.5 25.503 720 25.503C520.5 25.503 247.5 50.503 0 100V0Z" fill={curveColor || '#FFFDF5'} />
                        </svg>
                    </div>
                )}

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

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

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