import { useBlockProps, InspectorControls, PanelColorSettings, MediaUpload } from '@wordpress/block-editor';
import { PanelBody, SelectControl, TextControl, Notice, Tooltip, Placeholder, Spinner, Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useEffect } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import ServerSideRender from '@wordpress/server-side-render';

/**
 * 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 {
        menuSlug,
        logoText,
        ctaText,
        ctaUrl,
        navBgColor,
        linkColor,
        btnBgColor,
        blockId,
        headerStyle,
        logoType,
        logoImageId,
        logoImageUrl,
        headerBgColor,
        siteTitleColor,
        btnTextColor,
        btnHoverBgColor,
        btnHoverTextColor
    } = 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]);

    // Fetch available WordPress menus
    const { menus, isLoadingMenus } = useSelect((select) => {
        const { getEntityRecords, isResolving } = select('core');

        return {
            menus: getEntityRecords('taxonomy', 'nav_menu', { per_page: -1 }) || [],
            isLoadingMenus: isResolving('core', 'getEntityRecords', ['taxonomy', 'nav_menu', { per_page: -1 }]),
        };
    }, []);

    const blockProps = useBlockProps({
        className: `alignfull block-${blockId} awt-child-author-header`,
    });

    // Build menu options for SelectControl
    const menuOptions = [
        { label: __('— Select a Menu —', 'author-website-templates'), value: '' },
        ...(menus?.map((menu) => ({
            label: menu.name,
            value: menu.slug,
        })) || [])
    ];

    const onSelectLogo = (media) => {
        setAttributes({
            logoImageId: media.id,
            logoImageUrl: media.url,
        });
    };

    // Construct Preview Styles
    const previewStyle = {
        '--awt-header-bg': headerBgColor || navBgColor,
        '--awt-title-color': siteTitleColor,
        '--awt-link-color': linkColor,
        '--awt-btn-bg': btnBgColor,
        '--awt-btn-text': btnTextColor,
        '--awt-btn-hover-bg': btnHoverBgColor,
        '--awt-btn-hover-text': btnHoverTextColor
    };

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    {/* Menu Selection */}
                    {isLoadingMenus ? (
                        <div style={{ padding: '12px', textAlign: 'center' }}>
                            <Spinner />
                            <p>{__('Loading menus...', 'author-website-templates')}</p>
                        </div>
                    ) : (
                        <SelectControl
                            label={__('Select Menu', 'author-website-templates')}
                            value={menuSlug}
                            options={menuOptions}
                            onChange={(value) => setAttributes({ menuSlug: value })}
                            help={menus?.length === 0 ? __('No menus found. Create one in Appearance → Menus', 'author-website-templates') : __('Choose a WordPress menu to display', 'author-website-templates')}
                        />
                    )}

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

                    {/* Logo Settings */}
                    <SelectControl
                        label={__('Logo Type', 'author-website-templates')}
                        value={logoType}
                        options={[
                            { label: 'Site Title', value: 'site_title' },
                            { label: 'Custom Text', value: 'custom' },
                            { label: 'Image', value: 'image' }
                        ]}
                        onChange={(value) => setAttributes({ logoType: value })}
                    />

                    {logoType === 'custom' && (
                        <TextControl
                            label={__('Logo Text', 'author-website-templates')}
                            value={logoText}
                            onChange={(value) => setAttributes({ logoText: value })}
                            placeholder="John Doe"
                        />
                    )}

                    {logoType === 'site_title' && (
                        <p className="description" style={{ marginBottom: '16px' }}>
                            {__('Displays the global Site Title configured in WordPress Settings.', 'author-website-templates')}
                        </p>
                    )}

                    {logoType === 'image' && (
                        <div className="awt-logo-upload" style={{ marginBottom: '16px' }}>
                            <MediaUpload
                                onSelect={onSelectLogo}
                                allowedTypes={['image']}
                                value={logoImageId}
                                render={({ open }) => (
                                    <Button variant="secondary" onClick={open}>
                                        {logoImageId ? __('Change Logo', 'author-website-templates') : __('Upload Logo', 'author-website-templates')}
                                    </Button>
                                )}
                            />
                            {logoImageUrl && (
                                <img
                                    src={logoImageUrl}
                                    alt="Logo Preview"
                                    style={{ marginTop: '10px', maxWidth: '150px', height: 'auto', display: 'block', border: '1px solid #ddd', padding: '4px', borderRadius: '4px', background: '#fff' }}
                                />
                            )}
                        </div>
                    )}

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

                    {/* CTA Button Settings */}
                    <h4 style={{ marginBottom: '12px', fontWeight: 'bold' }}>{__('CTA Button', 'author-website-templates')}</h4>
                    <TextControl
                        label={__('Button Text', 'author-website-templates')}
                        value={ctaText}
                        onChange={(value) => setAttributes({ ctaText: value })}
                        placeholder="Latest Book!"
                        help={__('Leave empty to hide button', 'author-website-templates')}
                    />
                    <TextControl
                        label={__('Button URL', 'author-website-templates')}
                        value={ctaUrl}
                        onChange={(value) => setAttributes({ ctaUrl: value })}
                        placeholder="#featured-book"
                        help={__('Leave empty to hide button', 'author-website-templates')}
                    />
                </PanelBody>

                <PanelBody title={__('Design Settings', 'author-website-templates')} initialOpen={false}>

                    <SelectControl
                        label={__('Layout Style', 'author-website-templates')}
                        value={attributes.headerStyle || 'fun'}
                        options={[
                            { label: 'Fun (Default)', value: 'fun' },
                            { label: 'Elegant (Clean & Serif)', value: 'elegant' }
                        ]}
                        onChange={(value) => setAttributes({ headerStyle: value })}
                    />

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

                    {!isPro && (
                        <Notice status="warning" isDismissible={false}>
                            {__('🔒 Upgrade to Pro to unlock styling controls', 'author-website-templates')}
                        </Notice>
                    )}

                    <ProLock isPro={isPro}>
                        <PanelColorSettings
                            title={__('Header Colors', 'author-website-templates')}
                            colorSettings={[
                                {
                                    value: headerBgColor || navBgColor,
                                    onChange: isPro ? (color) => setAttributes({ headerBgColor: color }) : undefined,
                                    label: __('Header Background', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                                {
                                    value: siteTitleColor,
                                    onChange: isPro ? (color) => setAttributes({ siteTitleColor: color }) : undefined,
                                    label: __('Site Title Color', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                                {
                                    value: linkColor,
                                    onChange: isPro ? (color) => setAttributes({ linkColor: color }) : undefined,
                                    label: __('Link Color', 'author-website-templates'),
                                    disableCustomColors: !isPro,
                                },
                            ]}
                        />

                        <PanelColorSettings
                            title={__('Button Colors', 'author-website-templates')}
                            initialOpen={false}
                            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 Color', '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>

            <div {...blockProps} style={previewStyle}>
                {menuSlug === '' ? (
                    <Placeholder
                        icon="menu"
                        label={__('Header (Child Author)', 'author-website-templates')}
                        instructions={__('Please select a menu from the sidebar to get started.', 'author-website-templates')}
                    />
                ) : (
                    <ServerSideRender
                        block="awt/child-author-header"
                        attributes={attributes}
                        LoadingResponsePlaceholder={() => (
                            <div style={{ padding: '40px', textAlign: 'center' }}>
                                <Spinner />
                                <p>{__('Loading header preview...', 'author-website-templates')}</p>
                            </div>
                        )}
                        ErrorResponsePlaceholder={({ response }) => (
                            <Placeholder
                                icon="warning"
                                label={__('Rendering Error', 'author-website-templates')}
                            >
                                <p>{response?.message || __('Unable to render header preview.', 'author-website-templates')}</p>
                            </Placeholder>
                        )}
                    />
                )}
            </div>
        </>
    );
}
