import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls, PanelColorSettings, RichText } from '@wordpress/block-editor';
import { PanelBody, TextControl, RangeControl, Button } from '@wordpress/components';
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,
        sectionBadge,
        sectionTitle,
        sectionDesc,
        events,
        bgColor,
        accentColor,
        paddingTop,
        paddingBottom,
        anchor
    } = attributes;

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

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

    // Dynamic CSS for Editor
    const cssSelectorId = attributes.anchor ? attributes.anchor : blockId;
    const dynamicStyles = `
        #${cssSelectorId} .awt-date-text { color: ${accentColor} !important; }
        #${cssSelectorId} .awt-category { color: ${accentColor} !important; }
        #${cssSelectorId} .awt-event-card:hover { border-color: ${accentColor} !important; }
        
        #${cssSelectorId} .awt-event-card:hover .awt-date-text,
        #${cssSelectorId} .awt-event-card:hover .awt-category {
             color: ${accentColor} !important;
        }

        ${bgColor ? `#${cssSelectorId} { background-color: ${bgColor} !important; }` : ''}
    `;

    const blockProps = useBlockProps({
        className: 'awt-author-pro-events relative py-24 bg-paper',
        id: attributes.anchor ? undefined : blockId,
        style: {
            paddingTop: `${paddingTop}px`,
            paddingBottom: `${paddingBottom}px`,
            backgroundColor: bgColor
        }
    });

    const updateEvent = (index, key, value) => {
        const newEvents = [...events];
        newEvents[index][key] = value;
        setAttributes({ events: newEvents });
    };

    const addEvent = () => {
        const newEvent = {
            id: Date.now(),
            day: '01',
            monthYear: 'Jan, 2026',
            category: 'Event Category',
            title: 'New Event Title',
            location: 'Location',
            time: '10:00 AM - 12:00 PM',
            btnText: 'Details',
            btnUrl: '#'
        };
        setAttributes({ events: [...events, newEvent] });
    };

    const removeEvent = (index) => {
        const newEvents = events.filter((_, i) => i !== index);
        setAttributes({ events: newEvents });
    };

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

            <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={__('Section Description', 'author-website-templates')}
                        value={sectionDesc}
                        onChange={(value) => setAttributes({ sectionDesc: value })}
                    />
                </PanelBody>

                <PanelBody title={__('Events', 'author-website-templates')} initialOpen={false}>
                    {events.map((event, index) => (
                        <div key={index} className="mb-6 p-4 border rounded bg-gray-50">
                            <div className="flex justify-between items-center mb-2">
                                <span className="font-bold">Event {index + 1}</span>
                                <Button isDestructive isSmall onClick={() => removeEvent(index)}>
                                    Remove
                                </Button>
                            </div>

                            <div className="flex gap-2">
                                <TextControl
                                    label={__('Day', 'author-website-templates')}
                                    value={event.day}
                                    onChange={(value) => updateEvent(index, 'day', value)}
                                    className="w-1/3"
                                />
                                <TextControl
                                    label={__('Month/Year', 'author-website-templates')}
                                    value={event.monthYear}
                                    onChange={(value) => updateEvent(index, 'monthYear', value)}
                                    className="w-2/3"
                                />
                            </div>

                            <TextControl
                                label={__('Category', 'author-website-templates')}
                                value={event.category}
                                onChange={(value) => updateEvent(index, 'category', value)}
                            />
                            <TextControl
                                label={__('Title', 'author-website-templates')}
                                value={event.title}
                                onChange={(value) => updateEvent(index, 'title', value)}
                            />

                            <div className="flex gap-2">
                                <TextControl
                                    label={__('Location', 'author-website-templates')}
                                    value={event.location}
                                    onChange={(value) => updateEvent(index, 'location', value)}
                                    className="w-1/2"
                                />
                                <TextControl
                                    label={__('Time', 'author-website-templates')}
                                    value={event.time}
                                    onChange={(value) => updateEvent(index, 'time', value)}
                                    className="w-1/2"
                                />
                            </div>

                            <div className="flex gap-2">
                                <TextControl
                                    label={__('Button Text', 'author-website-templates')}
                                    value={event.btnText}
                                    onChange={(value) => updateEvent(index, 'btnText', value)}
                                    className="w-1/2"
                                />
                                <TextControl
                                    label={__('Button URL', 'author-website-templates')}
                                    value={event.btnUrl}
                                    onChange={(value) => updateEvent(index, 'btnUrl', value)}
                                    className="w-1/2"
                                />
                            </div>
                        </div>
                    ))}

                    <ProLock isLocked={!isPro}>
                        <Button variant="primary" onClick={addEvent} className="w-full justify-center">
                            {__('Add New Event', 'author-website-templates')}
                        </Button>
                    </ProLock>
                </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={__('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'),
                            }
                        ]}
                    />
                </ProLock>
            </InspectorControls>

            {/* Canvas Render */}
            <div className="max-w-5xl mx-auto px-6 lg:px-8">
                <div className="text-center mb-16">
                    <RichText
                        tagName="span"
                        className="font-bold text-xs uppercase tracking-widest awt-category block mb-2"
                        value={sectionBadge}
                        onChange={(value) => setAttributes({ sectionBadge: value })}
                        placeholder="Badge"
                    />
                    <RichText
                        tagName="h2"
                        className="text-4xl font-serif font-bold text-primary mt-2"
                        value={sectionTitle}
                        onChange={(value) => setAttributes({ sectionTitle: value })}
                        placeholder={__('Section Title...', 'author-website-templates')}
                    />
                    <RichText
                        tagName="p"
                        className="text-secondary mt-4 max-w-2xl mx-auto"
                        value={sectionDesc}
                        onChange={(value) => setAttributes({ sectionDesc: value })}
                        placeholder={__('Section Description...', 'author-website-templates')}
                    />
                </div>

                <div className="space-y-6">
                    {events.map((event, index) => (
                        <div key={index} className="awt-event-card bg-white p-6 md:p-8 rounded-xl border border-gray-100 shadow-sm hover:shadow-lg transition duration-300 flex flex-col md:flex-row items-center gap-6 md:gap-12 group">
                            <div className="flex flex-col items-center justify-center min-w-[80px] text-center">
                                <RichText
                                    tagName="span"
                                    className="text-3xl font-serif font-bold text-primary transition awt-date-text group-hover:text-accent"
                                    value={event.day}
                                    onChange={(value) => updateEvent(index, 'day', value)}
                                    placeholder="DD"
                                />
                                <RichText
                                    tagName="span"
                                    className="text-xs font-bold text-gray-400 uppercase tracking-wider"
                                    value={event.monthYear}
                                    onChange={(value) => updateEvent(index, 'monthYear', value)}
                                    placeholder="Month, Year"
                                />
                            </div>

                            <div className="flex-1 text-center md:text-left border-t md:border-t-0 md:border-l border-gray-100 pt-4 md:pt-0 md:pl-10 w-full">
                                <RichText
                                    tagName="span"
                                    className="text-xs font-bold awt-category text-accent uppercase mb-1 block"
                                    value={event.category}
                                    onChange={(value) => updateEvent(index, 'category', value)}
                                    placeholder="Category"
                                />
                                <RichText
                                    tagName="h3"
                                    className="text-xl font-bold text-primary mb-2"
                                    value={event.title}
                                    onChange={(value) => updateEvent(index, 'title', value)}
                                    placeholder="Event Title"
                                />
                                <div className="flex flex-wrap justify-center md:justify-start gap-4 text-sm text-secondary">
                                    <span className="flex items-center gap-2">
                                        <i className="fas fa-map-marker-alt text-gray-400"></i>
                                        <RichText
                                            tagName="span"
                                            value={event.location}
                                            onChange={(value) => updateEvent(index, 'location', value)}
                                            placeholder="Location"
                                        />
                                    </span>
                                    <span className="flex items-center gap-2">
                                        <i className="far fa-clock text-gray-400"></i>
                                        <RichText
                                            tagName="span"
                                            value={event.time}
                                            onChange={(value) => updateEvent(index, 'time', value)}
                                            placeholder="Time"
                                        />
                                    </span>
                                </div>
                            </div>

                            {event.btnUrl ? (
                                <button className="px-6 py-3 border border-primary bg-white text-primary font-bold text-xs uppercase rounded hover:bg-primary hover:text-white transition whitespace-nowrap">
                                    {event.btnText}
                                </button>
                            ) : (
                                <span className="px-6 py-3 border border-primary bg-white text-primary font-bold text-xs uppercase rounded hover:bg-primary hover:text-white transition whitespace-nowrap">
                                    {event.btnText || 'Sold Out'}
                                </span>
                            )}
                        </div>
                    ))}

                    <ProLock isLocked={!isPro}>
                        <div
                            role="button"
                            onClick={addEvent}
                            className="w-full border-2 border-dashed border-gray-300 rounded-xl p-8 flex flex-col items-center justify-center text-gray-400 hover:border-primary hover:text-primary hover:bg-gray-50 transition cursor-pointer group"
                        >
                            <div className="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center group-hover:bg-white transition mb-3">
                                <svg xmlns="http://www.w3.org/2000/svg" className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                                </svg>
                            </div>
                            <span className="font-bold text-sm uppercase tracking-wider">{__('Add New Event', 'author-website-templates')}</span>
                        </div>
                    </ProLock>
                </div>
            </div>
        </div>
    );
}
