import { useBlockProps, RichText, MediaUpload, MediaUploadCheck, InspectorControls, PanelColorSettings } from '@wordpress/block-editor';
import { PanelBody, Button, TextControl, RangeControl, Notice, Tooltip, TextareaControl, SelectControl } 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 {
        bookCoverId,
        featuredStyle,
        bookCoverUrl,
        badgeText,
        bookTitle,
        bookDesc,
        quoteText,
        quoteAuthor,
        btnText,
        btnUrl,
        sectionBgColor,
        sectionPadding,
        badgeColor,
        titleColor,
        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]);

    // Conditional class rendering to avoid !important conflicts
    const isFun = featuredStyle === 'fun';
    const isElegant = featuredStyle === 'elegant';

    const containerClass = sectionBgColor || sectionPadding !== null
        ? ''
        : 'py-24';

    // Container Grid Gap Class
    const gridGapClass = isElegant ? 'gap-16' : 'gap-12';

    // Image Styles
    const imageClass = isElegant
        ? 'rounded shadow-2xl w-full max-w-sm hover:scale-[1.02] transition-transform duration-500'
        : 'rounded-lg shadow-2xl max-w-sm w-full transition-transform duration-300 hover:scale-105 transform -rotate-2';

    const imgContainerClass = isElegant
        ? 'flex justify-center md:justify-end'
        : 'flex justify-center';

    // Badge Styles
    let badgeClass = badgeColor
        ? 'font-bold uppercase tracking-wider'
        : 'font-bold text-coral-pop uppercase tracking-wider';

    if (isElegant) {
        badgeClass = badgeColor
            ? 'block mb-2 text-xs uppercase tracking-widest font-bold'
            : 'block mb-2 text-xs uppercase tracking-widest font-bold text-gray-500';
    }

    // Title Styles
    let titleClass = titleColor
        ? 'text-4xl font-black mt-2 mb-6'
        : 'text-4xl font-black text-navy mt-2 mb-6';

    if (isElegant) {
        titleClass = titleColor
            ? 'text-4xl font-serif font-bold mt-2 mb-6'
            : 'text-4xl font-serif font-bold text-slate-800 mt-2 mb-6';
    }

    // Description Styles
    let descClass = 'text-lg text-navy/80 mb-6';
    if (isElegant) {
        descClass = 'text-lg text-gray-500 leading-relaxed mb-6';
    }

    // Quote Styles
    let quoteClass = 'border-l-4 border-yellow-sun pl-6 italic text-navy/70 my-8 text-lg';
    let quoteAuthorClass = 'block not-italic font-bold text-navy mt-2';

    if (isElegant) {
        quoteClass = 'border-l-4 border-slate-900 pl-6 italic text-gray-500 my-8 text-lg font-serif';
        quoteAuthorClass = 'block not-italic font-bold text-xs uppercase tracking-wide text-gray-500 mt-4';
    }

    // Button Styles
    let btnClass = btnBgColor
        ? 'btn-fun btn-order'
        : 'btn-fun btn-yellow btn-order';

    if (isElegant) {
        btnClass = btnBgColor
            ? 'px-8 py-3 rounded font-medium transition-all duration-300 ease-in-out border border-transparent shadow-sm hover:shadow-md btn-order'
            : 'px-8 py-3 rounded font-medium transition-all duration-300 ease-in-out border border-transparent bg-slate-900 text-white shadow-sm hover:shadow-md btn-order';
    }

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

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

    const onSelectBookCover = (media) => {
        setAttributes({
            bookCoverId: media.id,
            bookCoverUrl: media.url,
        });
    };

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    <SelectControl
                        label={__('Block Style', 'author-website-templates')}
                        value={featuredStyle}
                        options={[
                            { label: __('Fun (Child)', 'author-website-templates'), value: 'fun' },
                            { label: __('Elegant (Author)', 'author-website-templates'), value: 'elegant' },
                        ]}
                        onChange={(value) => setAttributes({ featuredStyle: value })}
                        help={__('Switch between the playful child theme and the elegant author portfolio style.', 'author-website-templates')}
                    />
                    <hr style={{ margin: '16px 0' }} />
                    {/* Book Cover Image Upload */}
                    <div className="sidebar-image-control" style={{ marginBottom: '16px' }}>
                        <p style={{ marginBottom: '8px', fontWeight: 'bold' }}>{__('Book Cover', 'author-website-templates')}</p>
                        <MediaUploadCheck>
                            <MediaUpload
                                onSelect={onSelectBookCover}
                                allowedTypes={['image']}
                                value={bookCoverId}
                                render={({ open }) => (
                                    <>
                                        {bookCoverUrl ? (
                                            <>
                                                <img src={bookCoverUrl} alt="Book Cover 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({ bookCoverId: 0, bookCoverUrl: '' })}>
                                                    {__('Remove', 'author-website-templates')}
                                                </Button>
                                            </>
                                        ) : (
                                            <Button variant="primary" onClick={open} style={{ width: '100%' }}>
                                                {__('Upload Image', 'author-website-templates')}
                                            </Button>
                                        )}
                                    </>
                                )}
                            />
                        </MediaUploadCheck>
                    </div>

                    {/* Text Content Controls */}
                    <TextControl
                        label={__('Badge Text', 'author-website-templates')}
                        value={badgeText}
                        onChange={(value) => setAttributes({ badgeText: value })}
                        help={__('You can also edit directly on the canvas', 'author-website-templates')}
                    />

                    <TextareaControl
                        label={__('Book Title', 'author-website-templates')}
                        value={bookTitle}
                        onChange={(value) => setAttributes({ bookTitle: value })}
                        rows={2}
                        help={__('You can also edit directly on the canvas', 'author-website-templates')}
                    />

                    <TextareaControl
                        label={__('Book Description', 'author-website-templates')}
                        value={bookDesc}
                        onChange={(value) => setAttributes({ bookDesc: value })}
                        rows={4}
                        help={__('You can also edit directly on the canvas', 'author-website-templates')}
                    />

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

                    <h4 style={{ marginBottom: '12px', fontWeight: 'bold' }}>{__('Testimonial Quote', 'author-website-templates')}</h4>
                    <TextareaControl
                        label={__('Quote Text', 'author-website-templates')}
                        value={quoteText}
                        onChange={(value) => setAttributes({ quoteText: value })}
                        rows={3}
                    />

                    <TextControl
                        label={__('Quote Author', 'author-website-templates')}
                        value={quoteAuthor}
                        onChange={(value) => setAttributes({ quoteAuthor: value })}
                        placeholder="— Sarah, Parent"
                    />

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

                    <h4 style={{ marginBottom: '12px', fontWeight: 'bold' }}>{__('Call to Action Button', 'author-website-templates')}</h4>
                    <TextControl
                        label={__('Button Text', 'author-website-templates')}
                        value={btnText}
                        onChange={(value) => setAttributes({ btnText: value })}
                    />

                    <TextControl
                        label={__('Button URL', 'author-website-templates')}
                        value={btnUrl}
                        onChange={(value) => setAttributes({ btnUrl: value })}
                        placeholder="#"
                    />
                </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: badgeColor,
                                    onChange: isPro ? (color) => setAttributes({ badgeColor: color }) : undefined,
                                    label: __('Badge Color', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                                {
                                    value: titleColor,
                                    onChange: isPro ? (color) => setAttributes({ titleColor: color }) : undefined,
                                    label: __('Title 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: __('Background', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                                {
                                    value: btnTextColor,
                                    onChange: isPro ? (color) => setAttributes({ btnTextColor: color }) : undefined,
                                    label: __('Text Color', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                                {
                                    value: btnHoverBgColor,
                                    onChange: isPro ? (color) => setAttributes({ btnHoverBgColor: color }) : undefined,
                                    label: __('Hover Background', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                                {
                                    value: btnHoverTextColor,
                                    onChange: isPro ? (color) => setAttributes({ btnHoverTextColor: color }) : undefined,
                                    label: __('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 grid md:grid-cols-2 ${gridGapClass} items-center`}>
                    {/* Left Column - Book Cover */}
                    <div className={imgContainerClass}>
                        <MediaUpload
                            onSelect={onSelectBookCover}
                            allowedTypes={['image']}
                            value={bookCoverId}
                            render={({ open }) => (
                                <figure className={imageClass} onClick={open}>
                                    {bookCoverUrl ? (
                                        <img src={bookCoverUrl} alt="The book cover for Featured Book" />
                                    ) : (
                                        <div className="bg-gray-200 aspect-[2/3] flex items-center justify-center">
                                            <Button variant="primary" onClick={open}>
                                                {__('Upload Book Cover', 'author-website-templates')}
                                            </Button>
                                        </div>
                                    )}
                                </figure>
                            )}
                        />
                    </div>

                    {/* Right Column - Content */}
                    <div>
                        <RichText
                            tagName="span"
                            className={badgeClass}
                            value={badgeText}
                            onChange={(value) => setAttributes({ badgeText: value })}
                            placeholder={__('Badge text...', 'author-website-templates')}
                            style={{ color: badgeColor || undefined }}
                        />

                        <RichText
                            tagName="h2"
                            className={titleClass}
                            value={bookTitle}
                            onChange={(value) => setAttributes({ bookTitle: value })}
                            placeholder={__('Book title...', 'author-website-templates')}
                            style={{ color: titleColor || undefined }}
                        />

                        <RichText
                            tagName="p"
                            className={descClass}
                            value={bookDesc}
                            onChange={(value) => setAttributes({ bookDesc: value })}
                            placeholder={__('Book description...', 'author-website-templates')}
                        />

                        <blockquote className={quoteClass}>
                            <RichText
                                tagName="p"
                                value={quoteText}
                                onChange={(value) => setAttributes({ quoteText: value })}
                                placeholder={__('Quote text...', 'author-website-templates')}
                            />
                            <RichText
                                tagName="cite"
                                className={quoteAuthorClass}
                                value={quoteAuthor}
                                onChange={(value) => setAttributes({ quoteAuthor: value })}
                                placeholder={__('Quote author...', 'author-website-templates')}
                            />
                        </blockquote>

                        <div className="buttons flex gap-4">
                            <RichText
                                tagName="span"
                                value={btnText}
                                onChange={(value) => setAttributes({ btnText: value })}
                                placeholder={__('Button text...', 'author-website-templates')}
                                className={btnClass}
                                style={{
                                    backgroundColor: btnBgColor || (isElegant ? '#0f172a' : undefined),
                                    color: btnTextColor || (isElegant ? '#ffffff' : undefined),
                                }}
                            />
                        </div>
                    </div>
                </div>
            </section>
        </>
    );
}
