import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls, PanelColorSettings, MediaUpload } from '@wordpress/block-editor';
import { PanelBody, TextControl, RangeControl, SelectControl, Button, ToggleControl } from '@wordpress/components';
import ServerSideRender from '@wordpress/server-side-render';
import { useEffect } from '@wordpress/element';

/**
 * ProLock Component
 */
const ProLock = ({ isLocked, children }) => {
    if (!isLocked) {
        return children;
    }
    return (
        <div style={{ position: 'relative', opacity: 0.5 }}>
            <div style={{ pointerEvents: 'none' }}>
                {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: 20,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    cursor: 'pointer',
                    background: 'rgba(255, 255, 255, 0.4)',
                }}
                title={__('Click to Upgrade to Pro', 'author-website-templates')}
            >
                <div style={{
                    background: '#fff',
                    padding: '6px 12px',
                    borderRadius: '4px',
                    boxShadow: '0 2px 5px rgba(0,0,0,0.1)',
                    fontSize: '12px',
                    fontWeight: 'bold',
                    color: '#333'
                }}>
                    🔒 Upgrade to Pro
                </div>
            </a>
        </div>
    );
};

export default function Edit({ attributes, setAttributes }) {
    const {
        blockId,
        sectionTitle,
        sectionBadge,
        postType,
        postsToShow,
        order,
        orderBy,
        selectedCategory,
        includePostIds,
        accentColor,
        btnColor,
        btnHoverColor,
        paddingTop,
        paddingBottom,
        buttonText,
        buttonIconId,
        buttonIconUrl,
        btnTextColor,
        btnHoverTextColor,
        showViewAllBtn,
        viewAllBtnText,

        viewAllBtnLink,
        anchor
    } = attributes;

    const isPro = window.awtVars?.isPro || false;

    // Generate unique ID if missing
    useEffect(() => {
        if (!blockId) {
            setAttributes({ blockId: `author-pro-books-${Math.floor(Math.random() * 10000)}` });
        }
    }, [blockId, setAttributes]);

    // Determine which ID to use for CSS selectors
    // If user sets an anchor, styles should target that anchor ID.
    const cssSelectorId = anchor ? anchor : blockId;

    // Dynamic CSS for Editor Preview
    const dynamicStyles = `
        #${cssSelectorId} .awt-dynamic-accent { color: ${accentColor} !important; }
        #${cssSelectorId} .awt-dynamic-accent-hover:hover { color: ${accentColor} !important; }

        #${cssSelectorId} .awt-buy-btn {
            background-color: ${btnColor || '#1e293b'}; /* Default slate-900 */
            color: ${btnTextColor || '#ffffff'} !important;
            transition: all 0.3s ease;
        }

        #${cssSelectorId} .awt-buy-btn:hover {
            background-color: ${btnHoverColor || accentColor || '#000'} !important;
            color: ${btnHoverTextColor || '#ffffff'} !important;
        }
    `;

    const blockProps = useBlockProps({
        className: 'awt-author-pro-books relative',
        id: anchor ? undefined : blockId
    });

    const onSelectIcon = (media) => {
        setAttributes({
            buttonIconId: media.id,
            buttonIconUrl: media.url,
        });
    };

    const removeIcon = () => {
        setAttributes({
            buttonIconId: 0,
            buttonIconUrl: '',
        });
    };

    return (
        <div {...blockProps}>
            <style>{dynamicStyles}</style>

            <InspectorControls>
                <PanelBody title={__('Query Settings', 'author-website-templates')} initialOpen={true}>
                    <TextControl
                        label={__('Post Type', 'author-website-templates')}
                        value={postType}
                        onChange={(value) => setAttributes({ postType: value })}
                        help={__('e.g. book, post', 'author-website-templates')}
                    />
                    <RangeControl
                        label={__('Number of Items', 'author-website-templates')}
                        value={postsToShow}
                        onChange={(value) => setAttributes({ postsToShow: value })}
                        min={1}
                        max={12}
                    />
                    <SelectControl
                        label={__('Order', 'author-website-templates')}
                        value={order}
                        options={[
                            { label: 'Descending (Newest First)', value: 'desc' },
                            { label: 'Ascending (Oldest First)', value: 'asc' },
                        ]}
                        onChange={(value) => setAttributes({ order: value })}
                    />
                    <TextControl
                        label={__('Filter by Category ID', 'author-website-templates')}
                        value={selectedCategory}
                        onChange={(value) => setAttributes({ selectedCategory: value })}
                        help={__('Enter a single Category ID (e.g. 5)', 'author-website-templates')}
                    />
                    <TextControl
                        label={__('Specific Post IDs', 'author-website-templates')}
                        value={includePostIds}
                        onChange={(value) => setAttributes({ includePostIds: value })}
                        help={__('Comma separated IDs (e.g. 101, 102). Overrides other filters.', 'author-website-templates')}
                    />
                </PanelBody>

                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={false}>
                    <TextControl
                        label={__('Section Badge', 'author-website-templates')}
                        value={sectionBadge}
                        onChange={(value) => setAttributes({ sectionBadge: value })}
                    />
                    <TextControl
                        label={__('Section Title', 'author-website-templates')}
                        value={sectionTitle}
                        onChange={(value) => setAttributes({ sectionTitle: value })}
                    />
                    <hr />
                    <TextControl
                        label={__('Cards - Buy Button Text', 'author-website-templates')}
                        value={buttonText}
                        onChange={(value) => setAttributes({ buttonText: value })}
                    />

                    <p className="components-base-control__label">{__('Cards - Button Icon', 'author-website-templates')}</p>
                    <div className="flex items-center gap-4 mb-4">
                        {buttonIconUrl && (
                            <img src={buttonIconUrl} alt="Icon" className="w-8 h-8 object-contain" />
                        )}
                        <MediaUpload
                            onSelect={onSelectIcon}
                            type="image"
                            value={buttonIconId}
                            render={({ open }) => (
                                <Button onClick={open} variant="secondary">
                                    {buttonIconUrl ? __('Replace Icon', 'author-website-templates') : __('Upload Icon', 'author-website-templates')}
                                </Button>
                            )}
                        />
                        {buttonIconUrl && (
                            <Button onClick={removeIcon} isDestructive variant="link">
                                {__('Remove', 'author-website-templates')}
                            </Button>
                        )}
                    </div>
                </PanelBody>

                <PanelBody title={__('View All Button', 'author-website-templates')} initialOpen={false}>
                    <ToggleControl
                        label={__('Show View All Button', 'author-website-templates')}
                        checked={showViewAllBtn}
                        onChange={(value) => setAttributes({ showViewAllBtn: value })}
                    />
                    {showViewAllBtn && (
                        <>
                            <TextControl
                                label={__('Button Text', 'author-website-templates')}
                                value={viewAllBtnText}
                                onChange={(value) => setAttributes({ viewAllBtnText: value })}
                            />
                            <TextControl
                                label={__('Custom Link (Optional)', 'author-website-templates')}
                                value={viewAllBtnLink}
                                onChange={(value) => setAttributes({ viewAllBtnLink: value })}
                                help={__('Leave empty to use the automatic Book Archive link.', 'author-website-templates')}
                            />
                        </>
                    )}
                </PanelBody>
            </InspectorControls>

            <InspectorControls group="styles">
                <PanelBody title={__('Spacing', 'author-website-templates')} initialOpen={true}>
                    <RangeControl
                        label={__('Top Padding (px)', 'author-website-templates')}
                        value={paddingTop}
                        onChange={(value) => setAttributes({ paddingTop: value })}
                        min={0}
                        max={300}
                    />
                    <RangeControl
                        label={__('Bottom Padding (px)', 'author-website-templates')}
                        value={paddingBottom}
                        onChange={(value) => setAttributes({ paddingBottom: value })}
                        min={0}
                        max={300}
                    />
                </PanelBody>

                <ProLock isLocked={!isPro}>
                    <PanelColorSettings
                        title={__('Styling', 'author-website-templates')}
                        initialOpen={true}
                        colorSettings={[
                            {
                                value: accentColor,
                                onChange: (value) => setAttributes({ accentColor: value }),
                                label: __('Accent Color', 'author-website-templates'),
                            },
                            {
                                value: btnColor,
                                onChange: (value) => setAttributes({ btnColor: value }),
                                label: __('Button Background Color', 'author-website-templates'),
                            },
                            {
                                value: btnTextColor,
                                onChange: (value) => setAttributes({ btnTextColor: value }),
                                label: __('Button Text Color', 'author-website-templates'),
                            },
                            {
                                value: btnHoverColor,
                                onChange: (value) => setAttributes({ btnHoverColor: value }),
                                label: __('Button Hover Background', 'author-website-templates'),
                            },
                            {
                                value: btnHoverTextColor,
                                onChange: (value) => setAttributes({ btnHoverTextColor: value }),
                                label: __('Button Hover Text Color', 'author-website-templates'),
                            }
                        ]}
                    />
                </ProLock>
            </InspectorControls>

            <ServerSideRender
                block="awt/author-pro-books"
                attributes={attributes}
            />
        </div>
    );
}
