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,
        sectionTitle,
        postsToShow,
        order,
        anchor,
        align,
        selectedBookId,
        bgColor,
        cardBgColor,
        accentColor,
        textColor,
        authorColor,
        paddingTop,
        paddingBottom
    } = attributes;

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

    // Fetch Books
    const books = useSelect((select) => {
        return select('core').getEntityRecords('postType', 'book', {
            per_page: -1,
            status: 'publish',
        });
    }, []);

    const bookOptions = [
        { label: __('All Books', 'author-website-templates'), value: '0' },
        ...(books ? books.map(book => ({ label: book.title.rendered, value: String(book.id) })) : [])
    ];

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

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

    return (
        <div {...blockProps}>
            <InspectorControls>
                <PanelBody title={__('Query Settings', 'author-website-templates')} initialOpen={true}>
                    <TextControl
                        label={__('Section Title', 'author-website-templates')}
                        value={sectionTitle}
                        onChange={(value) => setAttributes({ sectionTitle: value })}
                    />
                    <RangeControl
                        label={__('Number of Reviews', '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 })}
                    />

                    <SelectControl
                        label={__('Filter by Book', 'author-website-templates')}
                        value={selectedBookId}
                        options={bookOptions}
                        onChange={(value) => setAttributes({ selectedBookId: value })}
                        help={__('Show reviews connected to a specific book.', 'author-website-templates')}
                    />
                </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: cardBgColor,
                                onChange: (value) => setAttributes({ cardBgColor: value }),
                                label: __('Card Background (Glass)', 'author-website-templates'),
                            },
                            {
                                value: accentColor,
                                onChange: (value) => setAttributes({ accentColor: value }),
                                label: __('Stars Color', 'author-website-templates'),
                            },
                            {
                                value: textColor,
                                onChange: (value) => setAttributes({ textColor: value }),
                                label: __('Review Text Color', 'author-website-templates'),
                            },
                            {
                                value: authorColor,
                                onChange: (value) => setAttributes({ authorColor: value }),
                                label: __('Author Name Color', 'author-website-templates'),
                            },
                        ]}
                    />
                </ProLock>
            </InspectorControls>

            <ServerSideRender
                block={metadata.name}
                attributes={attributes}
            />
        </div>
    );
}
