import { __ } from '@wordpress/i18n';
import { useBlockProps, RichText, InspectorControls, PanelColorSettings } from '@wordpress/block-editor';
import { PanelBody, RangeControl, TextControl, ToggleControl, Spinner, Tooltip, Notice, SelectControl } from '@wordpress/components';
import { useSelect } from '@wordpress/data';

const ProLock = ({ isPro, children }) => {
    if (isPro) return children;
    return (
        <div className="pro-lock-wrapper relative group cursor-not-allowed">
            <div className="opacity-40 pointer-events-none grayscale filter">{children}</div>
            <a href="https://rswpthemes.com/author-portfolio-pro-wordpress-theme/" target="_blank" rel="noopener noreferrer" className="absolute inset-0 z-10 cursor-pointer" aria-label="Upgrade to Pro">
                <Tooltip text="🔒 Pro Feature - Click to Upgrade"><div className="w-full h-full" /></Tooltip>
            </a>
        </div>
    );
};

export default function Edit({ attributes, setAttributes, context }) {
    const {
        postsToShow,
        selectedBookId,
        heading,
        showCurve,
        curveColor,
        sectionBgColor,
        textColor,
        cardBgColor,
        starColor,
        reviewStyle,
    } = attributes;



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

    // Fetch Reviews for Preview
    const { reviews, hasResolved } = useSelect((select) => {
        const queryArgs = {
            per_page: postsToShow,
            status: 'publish',
            _embed: true,
        };

        // Note: Standard REST API filtering by multiple meta values is limited in Editor preview
        // We will attempt to filter if it's a single ID, otherwise show latest.
        if (selectedBookId && !selectedBookId.includes(',')) {
            queryArgs.meta_key = '_rswpbs_reviewed_book';
            queryArgs.meta_value = selectedBookId.trim();
        } else if (!selectedBookId && context.postType === 'book') {
            // Context Awareness: Auto-fetch for current book if no manual ID is set
            queryArgs.meta_key = '_rswpbs_reviewed_book';
            queryArgs.meta_value = context.postId;
        }

        return {
            reviews: select('core').getEntityRecords('postType', 'book_reviews', queryArgs),
            hasResolved: select('core').hasFinishedResolution('getEntityRecords', ['postType', 'book_reviews', queryArgs]),
        };
    }, [postsToShow, selectedBookId, context.postId, context.postType]);

    // Styles
    const isFun = reviewStyle === 'fun';
    const isElegant = reviewStyle === 'elegant';

    // Styles
    const sectionClass = sectionBgColor ? '' : (isElegant ? 'bg-gray-50' : 'bg-blue-sky/10');
    const sectionStyle = sectionBgColor ? { backgroundColor: sectionBgColor } : {};

    // Heading Styles
    const defaultHeadingClass = isElegant
        ? 'text-3xl md:text-5xl font-serif font-bold text-brand-dark'
        : 'text-4xl md:text-5xl font-black text-navy';
    const textClass = textColor ? '' : 'text-navy'; // General text fallback
    const textStyle = textColor ? { color: textColor } : {};

    const cardClass = cardBgColor ? '' : (isElegant ? 'bg-white rounded shadow-sm hover:shadow-md transition-all duration-300' : 'bg-white rounded-xl shadow-lg');
    const cardStyle = cardBgColor ? { backgroundColor: cardBgColor } : {};

    const starClass = starColor ? '' : (isElegant ? 'text-slate-900 text-lg tracking-widest' : 'text-yellow-sun text-4xl');
    const starStyle = starColor ? { color: starColor } : {};

    // Review Text
    const reviewTextClass = isElegant
        ? 'text-brand-gray italic mb-6 leading-relaxed'
        : 'text-lg text-navy/80 italic'; // Fun default

    // Author Meta Styles
    const aMetaContainerClass = isElegant ? 'flex items-center gap-4 border-t border-gray-100 pt-4' : 'flex items-center gap-4';
    const authorNameClass = isElegant ? 'font-bold text-slate-800 font-serif' : 'font-black';
    const authorRoleClass = isElegant ? 'text-xs text-gray-500 uppercase' : 'text-sm opacity-60';


    const truncate = (str, limit) => {
        if (!str) return '';
        const words = str.replace(/<[^>]+>/g, '').split(/\s+/);
        if (words.length <= limit) return str.replace(/<[^>]+>/g, '');
        return words.slice(0, limit).join(' ') + '...';
    };

    const blockProps = useBlockProps({
        className: `awt-child-author-reviews relative py-24 overflow-hidden ${sectionClass}`,
        style: sectionStyle
    });

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Review Settings', 'author-website-templates')}>
                    <SelectControl
                        label={__('Review Style', 'author-website-templates')}
                        value={reviewStyle}
                        options={[
                            { label: __('Fun (Child)', 'author-website-templates'), value: 'fun' },
                            { label: __('Elegant (Author)', 'author-website-templates'), value: 'elegant' },
                        ]}
                        onChange={(value) => setAttributes({ reviewStyle: value })}
                        help={__('Choose between the playful child theme style or the elegant author portfolio style.', 'author-website-templates')}
                    />
                    <RangeControl
                        label={__('Number of Reviews to Show (Initial)', 'author-website-templates')}
                        value={postsToShow}
                        onChange={(value) => setAttributes({ postsToShow: value })}
                        min={1}
                        max={12}
                    />
                    <TextControl
                        label={__('Filter by Book IDs (comma separated)', 'author-website-templates')}
                        value={selectedBookId}
                        onChange={(value) => setAttributes({ selectedBookId: value })}
                        help={__('Enter Book IDs separated by commas (e.g., 10, 15, 20). Leave empty to show all.', 'author-website-templates')}
                    />
                    <ToggleControl
                        label={__('Show Top Wave Curve', 'author-website-templates')}
                        checked={showCurve}
                        onChange={(value) => setAttributes({ showCurve: value })}
                    />

                </PanelBody>
            </InspectorControls>

            <InspectorControls group="styles">
                {!isPro && (
                    <PanelBody>
                        <Notice status="warning" isDismissible={false}>
                            {__('🔒 Upgrade to Pro to unlock styling controls', 'author-website-templates')}
                        </Notice>
                    </PanelBody>
                )}
                <ProLock isPro={isPro}>
                    <PanelColorSettings
                        title={__('Colors', 'author-website-templates')}
                        initialOpen={true}
                        colorSettings={[
                            { value: sectionBgColor, onChange: (c) => setAttributes({ sectionBgColor: c }), label: __('Section Background') },
                            { value: textColor, onChange: (c) => setAttributes({ textColor: c }), label: __('Text Color') },
                            { value: cardBgColor, onChange: (c) => setAttributes({ cardBgColor: c }), label: __('Card Background') },
                            { value: starColor, onChange: (c) => setAttributes({ starColor: c }), label: __('Star Color') },
                            { value: curveColor, onChange: (c) => setAttributes({ curveColor: c }), label: __('Curve Color') },
                        ]}
                    />

                </ProLock>
            </InspectorControls>

            <div {...blockProps}>
                {showCurve && isFun && (
                    <div className="absolute top-0 left-0 w-full pointer-events-none">
                        <svg viewBox="0 0 1440 100" fill="none" preserveAspectRatio="none" style={{ width: '100%', height: 'auto' }}>
                            <path d="M0 0H1440V100C1192.5 50.503 919.5 25.503 720 25.503C520.5 25.503 247.5 50.503 0 100V0Z" fill={curveColor} />
                        </svg>
                    </div>
                )}

                <div className={`awt-container container mx-auto px-6 relative z-10 ${(showCurve && isFun) ? 'mt-12' : ''}`}>
                    <RichText
                        tagName="h2"
                        className={`section-heading mb-12 text-center md:text-center ${textClass ? textClass : defaultHeadingClass}`}
                        value={heading}
                        onChange={(value) => setAttributes({ heading: value })}
                        placeholder={__('Section Heading...', 'author-website-templates')}
                        style={textStyle}
                    />

                    {!hasResolved ? (
                        <div className="flex justify-center p-8"><Spinner /></div>
                    ) : reviews && reviews.length > 0 ? (
                        <>
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                                {reviews.map((review, index) => {
                                    const metaData = review.meta_data || {};
                                    const rating = metaData.rating ? parseInt(metaData.rating) : 5;
                                    const reviewerName = metaData.reviewer_name || review.title.rendered || 'Reader';
                                    const contentRaw = review.content?.raw || review.content?.rendered || '';
                                    const previewText = truncate(contentRaw, 25);

                                    let rotationClass = '';
                                    if (isFun) {
                                        rotationClass = 'shadow-lg';
                                        if (index % 3 === 0) rotationClass += ' transform rotate-1';
                                        else if (index % 3 === 1) rotationClass += ' transform -rotate-1';
                                        else rotationClass += ' transform rotate-2';
                                    }

                                    const initial = reviewerName.charAt(0).toUpperCase();
                                    const avatarColors = ['bg-coral-pop/20 text-coral-pop', 'bg-blue-sky/20 text-blue-sky', 'bg-yellow-sun/20 text-navy'];

                                    return (
                                        <div key={review.id} className={`p-8 rounded-xl ${cardClass} ${rotationClass}`} style={cardBgColor ? { backgroundColor: cardBgColor } : {}}>
                                            <div className={`mb-4 ${starClass}`} style={starColor ? { color: starColor } : {}}>
                                                {[...Array(5)].map((_, i) => (<span key={i}>{i < rating ? '★' : '☆'}</span>))}
                                            </div>
                                            <p className={`${reviewTextClass} ${textClass}`} style={textColor ? { color: textColor } : {}}>
                                                "{previewText}"
                                            </p>
                                            <div className={aMetaContainerClass}>
                                                {isFun && (
                                                    <div className={`w-12 h-12 rounded-full flex items-center justify-center font-black text-xl ${avatarColors[index % 3]}`}>{initial}</div>
                                                )}
                                                <div>
                                                    <h5 className={`${authorNameClass} ${textClass}`} style={textColor ? { color: textColor } : {}}>{reviewerName}</h5>
                                                    <span className={`${authorRoleClass} ${textClass}`} style={textColor ? { color: textColor } : {}}>Verified Reader</span>
                                                </div>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>

                        </>
                    ) : (
                        <div className="text-center p-8 border-2 border-dashed border-gray-300 rounded-lg bg-white/50">
                            <p className="text-gray-500 text-lg">No reviews found matching criteria.</p>
                        </div>
                    )}
                </div>
            </div>
        </>
    );
}