import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls, PanelColorSettings } from '@wordpress/block-editor';
import { PanelBody, RangeControl, SelectControl, TextControl } from '@wordpress/components';
import { useEffect } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import ServerSideRender from '@wordpress/server-side-render';
import metadata from './block.json';

/**
 * 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,
        sectionBadge,
        sectionTitle,
        viewAllText,
        viewAllUrl,
        postsToShow,
        selectedCategory,
        order,
        bgColor,
        accentColor,
        titleColor,
        textColor,
        paddingTop,
        paddingBottom,
        anchor
    } = attributes;

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

    // Fetch Categories
    const categories = useSelect((select) => {
        return select('core').getEntityRecords('taxonomy', 'category', {
            per_page: -1,
            hide_empty: true,
        });
    }, []);

    const categoryOptions = [
        { label: __('All Categories', 'author-website-templates'), value: '' },
        ...(categories ? categories.map(cat => ({ label: cat.name, value: String(cat.id) })) : [])
    ];

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

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

    });

    return (
        <div {...blockProps}>
            <InspectorControls>
                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    <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 })}
                    />
                    <TextControl
                        label={__('View All Link Text', 'author-website-templates')}
                        value={viewAllText}
                        onChange={(value) => setAttributes({ viewAllText: value })}
                    />
                    <TextControl
                        label={__('View All Link URL', 'author-website-templates')}
                        value={viewAllUrl}
                        onChange={(value) => setAttributes({ viewAllUrl: value })}
                    />
                </PanelBody>

                <PanelBody title={__('Query Settings', 'author-website-templates')} initialOpen={true}>
                    <SelectControl
                        label={__('Filter by Category', 'author-website-templates')}
                        value={selectedCategory}
                        options={categoryOptions}
                        onChange={(value) => setAttributes({ selectedCategory: value })}
                    />
                    <RangeControl
                        label={__('Number of Posts', 'author-website-templates')}
                        value={postsToShow}
                        onChange={(value) => setAttributes({ postsToShow: value })}
                        min={1}
                        max={12}
                    />
                    <SelectControl
                        label={__('Order', 'author-website-templates')}
                        value={order}
                        options={[
                            { label: 'Newest First', value: 'DESC' },
                            { label: 'Oldest First', value: 'ASC' },
                        ]}
                        onChange={(value) => setAttributes({ order: value })}
                    />
                    <div className="bg-blue-50 p-4 rounded text-sm text-blue-800">
                        {__('Note: This block displays real "Posts" from your dashboard.', 'author-website-templates')}
                    </div>
                </PanelBody>

                <PanelBody title={__('Spacing', 'author-website-templates')} initialOpen={false}>
                    <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>
            </InspectorControls>

            <InspectorControls group="styles">
                <ProLock isLocked={!isPro}>
                    <PanelColorSettings
                        title={__('Colors', 'author-website-templates')}
                        initialOpen={true}
                        colorSettings={[
                            {
                                value: bgColor,
                                onChange: (value) => setAttributes({ bgColor: value }),
                                label: __('Section Background', 'author-website-templates'),
                            },
                            {
                                value: accentColor,
                                onChange: (value) => setAttributes({ accentColor: value }),
                                label: __('Accent Color', 'author-website-templates'),
                            },
                            {
                                value: titleColor,
                                onChange: (value) => setAttributes({ titleColor: value }),
                                label: __('Title Color', 'author-website-templates'),
                            },
                            {
                                value: textColor,
                                onChange: (value) => setAttributes({ textColor: value }),
                                label: __('Text Color', 'author-website-templates'),
                            },
                        ]}
                    />
                </ProLock>
            </InspectorControls>

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