import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls, PanelColorSettings, MediaUpload, MediaUploadCheck, RichText } from '@wordpress/block-editor';
import { PanelBody, TextControl, RangeControl, Button, IconButton } from '@wordpress/components';
import ServerSideRender from '@wordpress/server-side-render';
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,
        sectionTitle,
        sectionSubtitle,
        activities,
        bgColor,
        cardBgColor,
        accentColor,
        paddingTop,
        paddingBottom,
        anchor
    } = attributes;

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

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

    // Dynamic CSS for Editor
    const cssSelectorId = attributes.anchor ? attributes.anchor : blockId;
    const dynamicStyles = `
        #${cssSelectorId} .awt-accent { color: ${accentColor} !important; }
        #${cssSelectorId} .awt-card-bg { background-color: ${cardBgColor} !important; }
        
        /* Icon box colors */
        #${cssSelectorId} .awt-icon-box {
            background-color: #fff7ed; /* orange-50 default */
            color: ${accentColor || '#f97316'}; /* accent or orange-500 default */
        }
        
        #${cssSelectorId} .awt-activity-card:hover .awt-icon-box {
             background-color: ${accentColor || '#f97316'} !important;
             color: #ffffff !important;
        }

        #${cssSelectorId} .awt-activity-card:hover {
            border-color: ${accentColor || '#f97316'} !important;
        }

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

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

    const updateActivity = (index, key, value) => {
        const newActivities = [...activities];
        newActivities[index][key] = value;
        setAttributes({ activities: newActivities });
    };

    const addActivity = () => {
        const newActivity = {
            id: Date.now(),
            title: 'New Activity',
            location: 'Description or Location',
            link: '#',
            linkText: 'Learn More',
            iconId: 0,
            iconUrl: '',
            svgContent: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640" class="w-8 h-8 fill-current"><path d="M437.5 91.1C452.5 73.9 474.2 64 497.1 64C540.7 64 576.1 99.4 576.1 143C576.1 165.8 566.2 187.6 549 202.6L347.7 377.8L337 367L273 303L262.2 292.3L437.5 91.1zM225.1 323C226 324 252 350 303 401L316.9 414.9L299.8 489.1C295.9 506.2 282.9 519.8 266 524.5L96.2 572L188.5 479.7C189.7 479.8 190.8 479.9 192 479.9C209.7 479.9 224 465.6 224 447.9C224 430.2 209.7 415.9 192 415.9C174.3 415.9 160 430.2 160 447.9C160 449.1 160.1 450.3 160.2 451.4L67.9 543.8L115.5 374C120.2 357.1 133.8 344.1 150.9 340.2L225.1 323z"/></svg>` // Default Pen SVG
        };
        setAttributes({ activities: [...activities, newActivity] });
    };

    const removeActivity = (index) => {
        const newActivities = activities.filter((_, i) => i !== index);
        setAttributes({ activities: newActivities });
    };

    const onSelectIcon = (index, media) => {
        const newActivities = [...activities];
        newActivities[index].iconId = media.id;
        newActivities[index].iconUrl = media.url;
        setAttributes({ activities: newActivities });
    };

    const removeIcon = (index) => {
        const newActivities = [...activities];
        newActivities[index].iconId = 0;
        newActivities[index].iconUrl = '';
        setAttributes({ activities: newActivities });
    }

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

            <InspectorControls>
                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    <TextControl
                        label={__('Section Title', 'author-website-templates')}
                        value={sectionTitle}
                        onChange={(value) => setAttributes({ sectionTitle: value })}
                    />
                    <TextControl
                        label={__('Section Subtitle', 'author-website-templates')}
                        value={sectionSubtitle}
                        onChange={(value) => setAttributes({ sectionSubtitle: value })}
                    />
                </PanelBody>

                <PanelBody title={__('Activities', 'author-website-templates')} initialOpen={false}>
                    {activities.map((activity, 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">Activity {index + 1}</span>
                                <Button isDestructive isSmall onClick={() => removeActivity(index)}>
                                    Remove
                                </Button>
                            </div>

                            <div className="mb-4">
                                <p className="mb-2 font-semibold text-xs uppercase text-gray-500">Icon</p>
                                <div className="flex items-center gap-4">
                                    {activity.iconUrl ? (
                                        <div className="border border-gray-200 p-2 rounded bg-white">
                                            <img src={activity.iconUrl} alt="Icon" className="w-8 h-8 object-contain" />
                                        </div>
                                    ) : (
                                        <div className="border border-gray-200 p-2 rounded bg-white w-12 h-12 flex items-center justify-center text-gray-300">
                                            {activity.svgContent ? (
                                                <div dangerouslySetInnerHTML={{ __html: activity.svgContent }} className="w-6 h-6" />
                                            ) : (
                                                <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 15h-2v-6h2v6zm0-8h-2V7h2v2z" /></svg>
                                            )}
                                        </div>
                                    )}

                                    <MediaUploadCheck>
                                        <MediaUpload
                                            onSelect={(media) => onSelectIcon(index, media)}
                                            type="image"
                                            value={activity.iconId}
                                            render={({ open }) => (
                                                <Button onClick={open} variant="secondary">
                                                    {activity.iconUrl ? __('Replace Icon', 'author-website-templates') : __('Upload Icon', 'author-website-templates')}
                                                </Button>
                                            )}
                                        />
                                    </MediaUploadCheck>

                                    {activity.iconUrl && (
                                        <Button onClick={() => removeIcon(index)} isDestructive variant="link">
                                            {__('Remove', 'author-website-templates')}
                                        </Button>
                                    )}
                                </div>
                            </div>

                            <TextControl
                                label={__('Title', 'author-website-templates')}
                                value={activity.title}
                                onChange={(value) => updateActivity(index, 'title', value)}
                            />
                            <TextControl
                                label={__('Location / Description', 'author-website-templates')}
                                value={activity.location}
                                onChange={(value) => updateActivity(index, 'location', value)}
                            />

                            <div className="flex gap-4">
                                <div className="w-1/2">
                                    <TextControl
                                        label={__('Link Text', 'author-website-templates')}
                                        value={activity.linkText}
                                        onChange={(value) => updateActivity(index, 'linkText', value)}
                                    />
                                </div>
                                <div className="w-1/2">
                                    <TextControl
                                        label={__('Link URL', 'author-website-templates')}
                                        value={activity.link}
                                        onChange={(value) => updateActivity(index, 'link', value)}
                                    />
                                </div>
                            </div>
                        </div>
                    ))}

                    <ProLock isLocked={!isPro}>
                        <Button variant="primary" onClick={addActivity} className="w-full justify-center">
                            {__('Add New Activity', '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: cardBgColor,
                                onChange: (value) => setAttributes({ cardBgColor: value }),
                                label: __('Card Background', 'author-website-templates'),
                            },
                            {
                                value: accentColor,
                                onChange: (value) => setAttributes({ accentColor: value }),
                                label: __('Accent Color', 'author-website-templates'),
                            }
                        ]}
                    />
                </ProLock>
            </InspectorControls>

            {/* Canvas Render */}
            <div className="awt-container">
                <div className="text-center mb-16">
                    <RichText
                        tagName="h2"
                        className="text-4xl font-serif font-bold text-primary mb-4"
                        value={sectionTitle}
                        onChange={(value) => setAttributes({ sectionTitle: value })}
                        placeholder={__('Section Title...', 'author-website-templates')}
                    />
                    <RichText
                        tagName="p"
                        className="text-lg text-secondary max-w-2xl mx-auto"
                        value={sectionSubtitle}
                        onChange={(value) => setAttributes({ sectionSubtitle: value })}
                        placeholder={__('Section Subtitle...', 'author-website-templates')}
                    />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 text-center">
                    {activities.map((activity, index) => (
                        <div key={index} className="awt-card-bg p-8 border border-gray-100 rounded-2xl hover:border-accent hover:shadow-lg transition duration-300 group flex flex-col items-center">

                            {/* Icon Wrapper - Click to Upload */}
                            <MediaUploadCheck>
                                <MediaUpload
                                    onSelect={(media) => onSelectIcon(index, media)}
                                    allowedTypes={['image']}
                                    value={activity.iconId}
                                    render={({ open }) => (
                                        <div
                                            onClick={open}
                                            className="awt-icon-box w-16 h-16 mx-auto bg-orange-50 text-accent rounded-full flex items-center justify-center text-2xl leading-none mb-6 group-hover:bg-accent group-hover:text-white transition duration-300 cursor-pointer"
                                            title={__('Click to change icon', 'author-website-templates')}
                                        >
                                            {activity.iconUrl ? (
                                                <img src={activity.iconUrl} alt="Icon" className="w-8 h-8 object-contain filter ml-0 group-hover:brightness-0 group-hover:invert transition duration-300" />
                                            ) : (
                                                <div className="w-8 h-8 ml-0 flex items-center justify-center filter group-hover:brightness-0 group-hover:invert transition duration-300">
                                                    {activity.svgContent ? (
                                                        <div className="flex items-center justify-center w-full h-full" dangerouslySetInnerHTML={{ __html: activity.svgContent }} />
                                                    ) : (
                                                        <svg xmlns="http://www.w3.org/2000/svg" className="w-8 h-8 fill-current" viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 15h-2v-6h2v6zm0-8h-2V7h2v2z" /></svg>
                                                    )}
                                                </div>
                                            )}
                                        </div>
                                    )}
                                />
                            </MediaUploadCheck>

                            <RichText
                                tagName="h3"
                                className="text-xl font-bold text-primary mb-3"
                                value={activity.title}
                                onChange={(value) => updateActivity(index, 'title', value)}
                                placeholder="Activity Title"
                            />
                            <RichText
                                tagName="p"
                                className="text-sm text-secondary leading-relaxed mb-6"
                                value={activity.location}
                                onChange={(value) => updateActivity(index, 'location', value)}
                                placeholder="Description"
                            />

                            {/* Read More Link */}
                            {activity.linkText && (
                                <div className="mt-auto inline-flex items-center gap-2 text-sm font-bold uppercase tracking-wider awt-accent group-hover:opacity-80 transition cursor-pointer">
                                    <RichText
                                        tagName="span"
                                        value={activity.linkText}
                                        onChange={(value) => updateActivity(index, 'linkText', value)}
                                        placeholder="Link Text"
                                    />
                                    <svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4 transition-transform group-hover:translate-x-1" viewBox="0 0 20 20" fill="currentColor">
                                        <path fillRule="evenodd" d="M12.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-2.293-2.293a1 1 0 010-1.414z" clipRule="evenodd" />
                                    </svg>
                                </div>
                            )}
                        </div>
                    ))}

                    {/* Add New Activity Card (Pro) */}
                    <div
                        onClick={isPro ? addActivity : null}
                        className={`border-2 border-dashed border-gray-300 rounded-2xl flex flex-col items-center justify-center p-8 cursor-pointer hover:border-gray-400 transition min-h-[300px] ${!isPro ? 'opacity-50 cursor-not-allowed' : ''}`}
                    >
                        <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                            <span className="text-3xl text-gray-400">+</span>
                        </div>
                        <p className="text-gray-500 font-bold">Add New Activity</p>
                        {!isPro && <span className="text-xs text-red-400 mt-2">Upgrade to Pro</span>}
                    </div>

                </div>
            </div>
        </div>
    );
}
