import { useBlockProps, RichText, InspectorControls, PanelColorSettings } from '@wordpress/block-editor';
import { PanelBody, TextControl, TextareaControl, Notice, Tooltip, SelectControl } 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>
    );
};

export default function Edit({ attributes, setAttributes, clientId }) {
    const { heading, subHeading, sectionBgColor, curveColor, headingColor, textColor, blockId, titleStyle, badgeText } = attributes;
    const isPro = window.awtVars?.isPro || false;

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

    // Conditional classes
    let headingClass = 'text-5xl md:text-7xl mb-4';
    if (titleStyle === 'elegant') {
        headingClass = 'text-5xl md:text-7xl font-serif font-bold mb-6';
        if (!headingColor) headingClass += ' text-brand-dark';
    } else if (titleStyle === 'author-pro') {
        headingClass = 'text-4xl md:text-5xl lg:text-6xl font-serif font-bold mb-6 leading-tight';
        if (!headingColor) headingClass += ' text-primary';
    } else {
        // Fun (default)
        headingClass = 'text-5xl md:text-7xl font-black mb-4';
        if (!headingColor) headingClass += ' text-navy';
    }

    let subHeadingClass = 'text-xl mx-auto';
    if (titleStyle === 'elegant') {
        subHeadingClass = 'text-xl max-w-2xl mx-auto font-light leading-relaxed';
        if (!textColor) subHeadingClass += ' text-brand-gray';
    } else if (titleStyle === 'author-pro') {
        subHeadingClass = 'text-lg leading-relaxed max-w-2xl mx-auto';
        if (!textColor) subHeadingClass += ' text-secondary';
    } else {
        // Fun (default)
        subHeadingClass = 'text-xl max-w-lg mx-auto';
        if (!textColor) subHeadingClass += ' text-navy/80';
    }

    let defaultBgColor;
    if (titleStyle === 'elegant') {
        defaultBgColor = '#f8fafc';
    } else if (titleStyle === 'author-pro') {
        defaultBgColor = ''; // Uses bg-paper class
    } else {
        defaultBgColor = 'rgba(0, 198, 255, 0.1)';
    }

    let containerClass = `alignfull block-${blockId} relative overflow-hidden pt-20 pb-28`;
    if (titleStyle === 'author-pro') {
        containerClass = `alignfull block-${blockId} relative pt-32 pb-20 bg-paper border-b border-gray-100 overflow-hidden`;
    }

    const blockProps = useBlockProps({
        className: containerClass,
        style: {
            backgroundColor: sectionBgColor || defaultBgColor,
        }
    });

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

                    {(titleStyle === 'elegant' || titleStyle === 'author-pro') && (
                        <TextControl
                            label={__('Badge Text', 'author-website-templates')}
                            value={badgeText}
                            onChange={(value) => setAttributes({ badgeText: value })}
                        />
                    )}
                </PanelBody>

                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={false}>
                    <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={__('Subheading', 'author-website-templates')}
                        value={subHeading}
                        onChange={(value) => setAttributes({ subHeading: value })}
                        rows={3}
                        help={__('You can also edit directly on the canvas', '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={__('Colors', 'author-website-templates')}
                            colorSettings={[
                                {
                                    value: sectionBgColor,
                                    onChange: (color) => setAttributes({ sectionBgColor: color }),
                                    label: __('Background Color', 'author-website-templates'),
                                },
                                {
                                    value: curveColor,
                                    onChange: (color) => setAttributes({ curveColor: color }),
                                    label: __('Bottom 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: __('Subheading Color', 'author-website-templates'),
                                },
                            ]}
                        />
                    </ProLock>
                </PanelBody>
            </InspectorControls>

            <section {...blockProps}>

                {/* Bottom SVG Wave - Only for Fun style */}
                {titleStyle !== 'elegant' && titleStyle !== 'author-pro' && (
                    <div className="absolute bottom-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 100H1440V0C1192.5 49.497 919.5 74.497 720 74.497C520.5 74.497 247.5 49.497 0 0V100Z" fill={curveColor || '#FFFDF5'} />
                        </svg>
                    </div>
                )}

                <div className={`awt-container mx-auto px-6 relative z-10 text-center ${titleStyle === 'author-pro' ? 'max-w-4xl' : ''}`}>

                    {titleStyle === 'elegant' && (
                        <RichText
                            tagName="span"
                            className="font-bold text-gray-500 uppercase tracking-widest text-xs mb-4 block"
                            value={badgeText}
                            onChange={(value) => setAttributes({ badgeText: value })}
                            placeholder={__('BIOGRAPHY', 'author-website-templates')}
                        />
                    )}

                    <RichText
                        tagName="h1"
                        className={headingClass}
                        value={heading}
                        onChange={(value) => setAttributes({ heading: value })}
                        placeholder={__('Enter page title...', 'author-website-templates')}
                        style={{ color: headingColor || undefined }}
                    />

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