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

// Default bio template (2 paragraphs)
const BIO_TEMPLATE = [
    ['core/paragraph', { content: "That's me! I've been writing stories since I was your age. I love creating characters who go on big adventures and learn important lessons about friendship and bravery." }],
    ['core/paragraph', { content: "When I'm not writing books about magical worlds and talking animals, you can find me reading, baking cookies, or playing with my dog, Max!" }],
];

export default function Edit({ attributes, setAttributes, clientId }) {
    const {
        heading,
        authorImageId,
        authorImageUrl,
        buttonText,
        buttonUrl,
        sectionBgColor,
        sectionPadding,
        headingColor,
        textColor,
        btnBgColor,
        btnTextColor,
        btnHoverBgColor,
        btnHoverTextColor,
        imageStyle,
        showButton,
        blockId,
        aboutStyle,
    } = 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 isElegant = aboutStyle === 'elegant';

    // Grid Layout & Spans
    const gridClass = isElegant
        ? 'grid md:grid-cols-5 gap-16 items-center'
        : 'grid md:grid-cols-2 gap-12 items-center';

    const imageColClass = isElegant
        ? 'md:col-span-2 flex justify-center order-2 md:order-1'
        : 'order-2 md:order-1';

    const textColClass = isElegant
        ? 'md:col-span-3 order-1 md:order-2'
        : 'order-1 md:order-2';

    // Styles
    const containerClass = sectionBgColor || sectionPadding !== null
        ? ''
        : (isElegant ? 'bg-gray-50' : 'bg-yellow-sun/20 py-24');

    const headingClass = headingColor
        ? (isElegant ? 'text-4xl font-serif font-bold text-brand-dark mb-6' : 'text-4xl font-black text-navy mb-6')
        : (isElegant ? 'text-4xl font-serif font-bold text-brand-dark mb-6' : 'text-4xl font-black text-navy mb-6');

    const bioClass = textColor
        ? (isElegant ? 'text-lg space-y-4 leading-relaxed' : 'text-lg mb-4 leading-relaxed')
        : (isElegant ? 'text-lg text-brand-gray space-y-4 leading-relaxed' : 'text-lg text-navy/80 mb-4 leading-relaxed');

    // Image Style Logic
    let finalImageStyle;
    if (isElegant) {
        finalImageStyle = imageStyle === 'portrait'
            ? 'rounded-lg shadow-xl aspect-[4/5] object-cover w-full max-w-sm border border-gray-100'
            : 'rounded-full overflow-hidden w-64 h-64 md:w-80 md:h-80 shadow-lg border-4 border-white object-cover';
    } else {
        finalImageStyle = imageStyle === 'portrait'
            ? 'rounded-lg shadow-xl aspect-[4/5] object-cover w-full max-w-sm transform -rotate-2 hover:rotate-2 transition-transform duration-300'
            : 'rounded-full shadow-xl aspect-square object-cover w-full max-w-sm';
    }

    const btnClass = btnBgColor
        ? (isElegant ? 'px-8 py-3 rounded font-medium border border-gray-800 text-gray-900 transition-colors inline-block' : 'btn-fun btn-white')
        : (isElegant ? 'px-8 py-3 rounded font-medium bg-white border border-gray-800 text-gray-900 hover:bg-gray-50 transition-colors inline-block' : 'btn-fun btn-white');

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

    const blockProps = useBlockProps({
        className: `alignfull block-${blockId} awt-child-author-about ${containerClass}`,
        style: {
            backgroundColor: sectionBgColor || undefined,
            paddingTop: sectionPadding !== null ? `${sectionPadding}px` : undefined,
            paddingBottom: sectionPadding !== null ? `${sectionPadding}px` : undefined,
        }
    });

    const innerBlocksProps = useInnerBlocksProps(
        { className: `about-bio-content ${bioClass}` },
        {
            allowedBlocks: ['core/paragraph', 'core/heading', 'core/list'],
            template: BIO_TEMPLATE,
        }
    );

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

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    <SelectControl
                        label={__('Block Style', 'author-website-templates')}
                        value={aboutStyle}
                        options={[
                            { label: __('Fun (Child)', 'author-website-templates'), value: 'fun' },
                            { label: __('Elegant (Author)', 'author-website-templates'), value: 'elegant' },
                        ]}
                        onChange={(value) => setAttributes({ aboutStyle: value })}
                    />
                    <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')}
                    />

                    {/* Author Image Upload */}
                    <div className="sidebar-image-control" style={{ marginBottom: '16px' }}>
                        <p style={{ marginBottom: '8px', fontWeight: 'bold' }}>{__('Author Image', 'author-website-templates')}</p>
                        <MediaUploadCheck>
                            <MediaUpload
                                onSelect={onSelectImage}
                                allowedTypes={['image']}
                                value={authorImageId}
                                render={({ open }) => (
                                    <>
                                        {authorImageUrl ? (
                                            <>
                                                <img src={authorImageUrl} alt="Author Preview" style={{ width: '100%', height: 'auto', marginBottom: '10px', borderRadius: '8px' }} />
                                                <Button variant="secondary" onClick={open} style={{ width: '100%', marginBottom: '8px' }}>
                                                    {__('Replace Image', 'author-website-templates')}
                                                </Button>
                                                <Button variant="link" isDestructive onClick={() => setAttributes({ authorImageId: 0, authorImageUrl: '' })}>
                                                    {__('Remove', 'author-website-templates')}
                                                </Button>
                                            </>
                                        ) : (
                                            <Button variant="primary" onClick={open} style={{ width: '100%' }}>
                                                {__('Upload Image', 'author-website-templates')}
                                            </Button>
                                        )}
                                    </>
                                )}
                            />
                        </MediaUploadCheck>
                    </div>

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

                    <h4 style={{ marginBottom: '12px', fontWeight: 'bold' }}>{__('Button Settings', 'author-website-templates')}</h4>
                    <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="#contact"
                    />

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

                    <h4 style={{ marginBottom: '12px', fontWeight: 'bold' }}>{__('Display Options', 'author-website-templates')}</h4>
                    <SelectControl
                        label={__('Image Style', 'author-website-templates')}
                        value={imageStyle}
                        options={[
                            { label: __('Circle (Default)', 'author-website-templates'), value: 'circle' },
                            { label: __('Portrait (Rounded + Rotated)', 'author-website-templates'), value: 'portrait' },
                        ]}
                        onChange={(value) => setAttributes({ imageStyle: value })}
                        help={__('Choose image shape for different page layouts', 'author-website-templates')}
                    />

                    <ToggleControl
                        label={__('Show CTA Button', 'author-website-templates')}
                        checked={showButton}
                        onChange={(value) => setAttributes({ showButton: value })}
                        help={__('Toggle button visibility for About Page variation', '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={__('Button Colors', 'author-website-templates')}
                            colorSettings={[
                                {
                                    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">
                    <div className={gridClass}>
                        {/* Left Column - Author Image */}
                        <div className={imageColClass}>
                            <MediaUpload
                                onSelect={onSelectImage}
                                allowedTypes={['image']}
                                value={authorImageId}
                                render={({ open }) => (
                                    <figure
                                        className="about-section-image-container"
                                        onClick={open}
                                    >
                                        {authorImageUrl ? (
                                            <img
                                                src={authorImageUrl}
                                                alt="Author photo"
                                                className={finalImageStyle}
                                            />
                                        ) : (
                                            <div className="bg-gray-200 aspect-[4/5] flex items-center justify-center">
                                                <Button variant="primary" onClick={open}>
                                                    {__('Upload Author Image', 'author-website-templates')}
                                                </Button>
                                            </div>
                                        )}
                                    </figure>
                                )}
                            />
                        </div>

                        {/* Right Column - Bio Text */}
                        <div className={textColClass}>
                            <RichText
                                tagName="h2"
                                className={headingClass}
                                value={heading}
                                onChange={(value) => setAttributes({ heading: value })}
                                placeholder={__('Enter heading...', 'author-website-templates')}
                                style={{ color: headingColor || undefined }}
                            />

                            <div {...innerBlocksProps} style={{ color: textColor || undefined }} />

                            {showButton && (
                                <div className="mt-8">
                                    <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,
                                            textDecoration: 'none',
                                        }}
                                    />
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </section>
        </>
    );
}
