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

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 }) {
    const {
        postsToShow, order, orderBy,
        sectionTitle, readMoreText, showDate, showCategory, showExcerpt, showReadMore,
        showViewAll, viewAllText, viewAllUrl,
        sectionBgColor, cardBgColor, titleColor, metaColor, readMoreColor, viewAllColor,
        storiesStyle
    } = attributes;

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

    // Fetch Posts
    const { posts, hasResolved } = useSelect((select) => {
        const queryArgs = {
            per_page: postsToShow,
            order: order,
            orderby: orderBy,
            _embed: true,
        };
        return {
            posts: select('core').getEntityRecords('postType', 'post', queryArgs),
            hasResolved: select('core').hasFinishedResolution('getEntityRecords', ['postType', 'post', queryArgs]),
        };
    }, [postsToShow, order, orderBy]);

    const isFun = storiesStyle === 'fun';
    const isElegant = storiesStyle === 'elegant';

    // Conditional Styles
    const containerBg = isElegant ? '#ffffff' : sectionBgColor; // Elegant forces white unless Pro overridden (handled by style prop if set)
    // Actually, for Elegant, we want to force white bg by default if sectionBgColor is default or empty. 
    // But sectionBgColor has a default. 
    // Let's rely on the classes and let sectionBgColor override if user changes it.

    // Header
    const headerClass = isElegant
        ? 'flex justify-between items-end mb-12 border-b border-gray-100 pb-6'
        : 'flex justify-between items-end mb-12';

    // Section Title
    const titleClass = isElegant
        ? 'text-3xl md:text-4xl font-serif font-bold text-brand-dark text-center md:text-left'
        : 'text-4xl font-black text-center md:text-left';

    // View All Link
    const viewAllClass = isElegant
        ? 'hidden md:inline-block font-medium text-brand-dark hover:text-gray-600 mb-2'
        : 'hidden md:inline-block font-bold transition-colors mb-2 text-blue-sky hover:text-navy';

    // Card Wrapper
    const cardWrapperClass = isElegant
        ? 'group cursor-pointer'
        : 'group cursor-pointer'; // Same wrapper for article, inner div changes

    const innerCardClass = isElegant
        ? '' // No bg/shadow for elegant
        : 'overflow-hidden rounded-xl shadow-lg mb-4 bg-white';

    // Image
    const imageWrapperClass = isElegant
        ? 'h-56 rounded-lg bg-gray-100 mb-4 overflow-hidden'
        : 'overflow-hidden rounded-t-xl';

    const imageClass = isElegant
        ? 'w-full h-full object-cover transition-transform duration-500 group-hover:scale-105'
        : 'w-full h-48 object-cover transition-transform duration-500 group-hover:scale-110';

    // Meta
    const metaClass = isElegant
        ? 'text-brand-gray font-bold text-xs uppercase tracking-widest block mb-1'
        : 'font-bold text-sm uppercase block mb-2';

    // Post Title
    const postTitleClass = isElegant
        ? 'text-xl font-serif font-bold text-brand-dark mt-2 group-hover:text-gray-600 transition-colors'
        : 'text-xl font-black mt-2 group-hover:opacity-75 transition-opacity';

    const blockProps = useBlockProps({
        className: 'awt-child-author-latest-stories py-24',
        style: { backgroundColor: isElegant && sectionBgColor === '#FFFDF5' ? '#ffffff' : sectionBgColor }
    });

    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(' ') + '...';
    };

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Query Settings', 'author-website-templates')}>
                    <SelectControl
                        label={__('Block Style', 'author-website-templates')}
                        value={storiesStyle}
                        options={[
                            { label: __('Fun (Child)', 'author-website-templates'), value: 'fun' },
                            { label: __('Elegant (Author)', 'author-website-templates'), value: 'elegant' },
                        ]}
                        onChange={(value) => setAttributes({ storiesStyle: 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: 'Descending (Newest First)', value: 'desc' },
                            { label: 'Ascending (Oldest First)', value: 'asc' },
                        ]}
                        onChange={(value) => setAttributes({ order: value })}
                    />
                    <SelectControl
                        label={__('Order By', 'author-website-templates')}
                        value={orderBy}
                        options={[
                            { label: 'Date', value: 'date' },
                            { label: 'Title', value: 'title' },
                        ]}
                        onChange={(value) => setAttributes({ orderBy: value })}
                    />
                </PanelBody>

                <PanelBody title={__('Header Settings', 'author-website-templates')}>
                    <ToggleControl
                        label={__('Show "View All" Link', 'author-website-templates')}
                        checked={showViewAll}
                        onChange={(value) => setAttributes({ showViewAll: value })}
                    />
                    {showViewAll && (
                        <>
                            <TextControl
                                label={__('Link Text', 'author-website-templates')}
                                value={viewAllText}
                                onChange={(value) => setAttributes({ viewAllText: value })}
                            />
                            <TextControl
                                label={__('Link URL', 'author-website-templates')}
                                value={viewAllUrl}
                                onChange={(value) => setAttributes({ viewAllUrl: value })}
                            />
                        </>
                    )}
                </PanelBody>

                <PanelBody title={__('Content Settings', 'author-website-templates')}>
                    <TextControl
                        label={__('Section Title', 'author-website-templates')}
                        value={sectionTitle}
                        onChange={(value) => setAttributes({ sectionTitle: value })}
                    />
                    <ToggleControl
                        label={__('Show Date', 'author-website-templates')}
                        checked={showDate}
                        onChange={(value) => setAttributes({ showDate: value })}
                    />
                    <ToggleControl
                        label={__('Show Category', 'author-website-templates')}
                        checked={showCategory}
                        onChange={(value) => setAttributes({ showCategory: value })}
                    />
                    <ToggleControl
                        label={__('Show Excerpt', 'author-website-templates')}
                        checked={showExcerpt}
                        onChange={(value) => setAttributes({ showExcerpt: value })}
                    />
                    <ToggleControl
                        label={__('Show Read More Link', 'author-website-templates')}
                        checked={showReadMore}
                        onChange={(value) => setAttributes({ showReadMore: value })}
                    />
                    {showReadMore && (
                        <TextControl
                            label={__('Read More Text', 'author-website-templates')}
                            value={readMoreText}
                            onChange={(value) => setAttributes({ readMoreText: 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: cardBgColor, onChange: (c) => setAttributes({ cardBgColor: c }), label: __('Card Background') },
                            { value: titleColor, onChange: (c) => setAttributes({ titleColor: c }), label: __('Title Color') },
                            { value: metaColor, onChange: (c) => setAttributes({ metaColor: c }), label: __('Meta (Date/Category) Color') },
                            { value: readMoreColor, onChange: (c) => setAttributes({ readMoreColor: c }), label: __('Read More Link Color') },
                            { value: viewAllColor, onChange: (c) => setAttributes({ viewAllColor: c }), label: __('View All Link Color') },
                        ]}
                    />
                </ProLock>
            </InspectorControls>

            <div {...blockProps}>
                <div className="awt-container mx-auto px-6">
                    <div className={headerClass}>
                        <RichText
                            tagName="h2"
                            className={titleClass}
                            value={sectionTitle}
                            onChange={(value) => setAttributes({ sectionTitle: value })}
                            style={{ color: titleColor }}
                            placeholder={__('Section Title...', 'author-website-templates')}
                        />
                        {showViewAll && (
                            <a
                                href="#"
                                className={viewAllClass}
                                style={viewAllColor ? { color: viewAllColor } : {}}
                                onClick={(e) => e.preventDefault()}
                            >
                                <span>
                                    {viewAllText}
                                </span>
                            </a>
                        )}
                    </div>

                    {!hasResolved ? (
                        <div className="flex justify-center p-8"><Spinner /></div>
                    ) : posts && posts.length > 0 ? (
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
                            {posts.map((post) => {
                                const title = decodeEntities(post.title.rendered);
                                const excerpt = post.excerpt.rendered ? truncate(post.excerpt.rendered, 20) : '';
                                const date = dateI18n('F j, Y', post.date);
                                const featuredMedia = post._embedded?.['wp:featuredmedia']?.[0]?.source_url;

                                const category = showCategory ? (post._embedded?.['wp:term']?.[0]?.[0]?.name || 'Stories') : '';

                                return (
                                    <article key={post.id} className={cardWrapperClass}>
                                        <div className={innerCardClass} style={isFun ? { minHeight: '200px', backgroundColor: cardBgColor } : {}}>
                                            <div className={imageWrapperClass}>
                                                {featuredMedia ? (
                                                    <img
                                                        src={featuredMedia}
                                                        alt={title}
                                                        className={imageClass}
                                                    />
                                                ) : (
                                                    <div className={`w-full h-full flex items-center justify-center text-gray-400 ${isFun ? 'bg-gray-200' : ''}`}>
                                                        {__('No Image', 'author-website-templates')}
                                                    </div>
                                                )}
                                            </div>
                                        </div>

                                        {(showDate || showCategory) && (
                                            <span
                                                className={metaClass}
                                                style={{ color: metaColor }}
                                            >
                                                {showDate && date}
                                                {showDate && showCategory && category && ' • '}
                                                {showCategory && category}
                                            </span>
                                        )}

                                        <h3
                                            className={postTitleClass}
                                            style={{ color: titleColor }}
                                        >
                                            {title}
                                        </h3>
                                        {showExcerpt && (
                                            <div
                                                className="text-gray-600 mt-2 text-base leading-relaxed"
                                                dangerouslySetInnerHTML={{ __html: excerpt }}
                                            />
                                        )}
                                        {showReadMore && (
                                            <div className="mt-4 font-bold hover:underline" style={{ color: readMoreColor || metaColor }}>
                                                {readMoreText} &rarr;
                                            </div>
                                        )}
                                    </article>
                                );
                            })}
                        </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 adventures found yet! Add some posts to see them here.', 'author-website-templates')}
                            </p>
                        </div>
                    )}
                </div>
            </div>
        </>
    );
}
