import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls, MediaUpload, MediaUploadCheck, PanelColorSettings } from '@wordpress/block-editor';
import { PanelBody, TextControl, Button, RangeControl } from '@wordpress/components';
import { useEffect } from '@wordpress/element';
import ServerSideRender from '@wordpress/server-side-render';

/**
 * ProLock Component - Wrapper for Pro-only controls
 * Shows controls but locks them with a clickable overlay if not Pro
 */
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)',
                }}
            >
                <div style={{
                    background: '#fff',
                    padding: '6px 12px',
                    borderRadius: '4px',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                    fontWeight: '500',
                    fontSize: '12px',
                    color: '#333',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '4px'
                }}>
                    <span role="img" aria-label="lock">🔒</span> {__('Upgrade', 'author-website-templates')}
                </div>
            </a>
        </div>
    );
};

export default function Edit({ attributes, setAttributes }) {
    const {
        blockId,
        sectionTitle,
        logos,
        paddingTop,
        paddingBottom,
        bgColor
    } = attributes;

    // Generate unique block ID
    useEffect(() => {
        if (!blockId) {
            setAttributes({ blockId: `featured-in-${Date.now()}` });
        }
    }, []);

    const blockProps = useBlockProps({
        className: 'awt-author-pro-featured-in-editor'
    });

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

    // Logo Management
    const addLogo = () => {
        setAttributes({
            logos: [
                ...logos,
                {
                    id: Date.now(),
                    text: 'New Logo',
                    url: '',
                    link: '#'
                }
            ]
        });
    };

    const updateLogo = (index, field, value) => {
        const newLogos = [...logos];
        newLogos[index] = { ...newLogos[index], [field]: value };
        setAttributes({ logos: newLogos });
    };

    const removeLogo = (index) => {
        const newLogos = logos.filter((_, i) => i !== index);
        setAttributes({ logos: newLogos });
    };

    const onSelectLogo = (index, media) => {
        const newLogos = [...logos];
        newLogos[index] = {
            ...newLogos[index],
            url: media.url,
            id: media.id,
            // If alt text exists, use it, otherwise keep existing or fallback
            alt: media.alt || newLogos[index].text || 'Logo'
        };
        setAttributes({ logos: newLogos });
    };

    return (
        <div {...blockProps}>
            {/* SETTINGS TAB */}
            <InspectorControls>
                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    <TextControl
                        label={__('Section Title', 'author-website-templates')}
                        value={sectionTitle}
                        onChange={(value) => setAttributes({ sectionTitle: value })}
                        placeholder={__('Featured In', 'author-website-templates')}
                    />

                    <hr style={{ margin: '16px 0' }} />

                    <h3>{__('Logos', 'author-website-templates')}</h3>
                    <div className="awt-logos-list">
                        {logos.map((logo, index) => (
                            <div key={index} style={{ marginBottom: '20px', padding: '15px', border: '1px solid #ddd', borderRadius: '4px' }}>
                                {/* Preview */}
                                <div style={{ marginBottom: '10px', textAlign: 'center', background: '#f0f0f0', padding: '10px', borderRadius: '4px' }}>
                                    {logo.url ? (
                                        <img src={logo.url} alt={logo.text} style={{ maxWidth: '100%', height: 'auto', maxHeight: '40px' }} />
                                    ) : (
                                        <span style={{ fontWeight: 'bold', textTransform: 'uppercase', color: '#666' }}>{logo.text || 'LOGO'}</span>
                                    )}
                                </div>

                                <TextControl
                                    label={__('Logo Text / Name', 'author-website-templates')}
                                    value={logo.text}
                                    onChange={(value) => updateLogo(index, 'text', value)}
                                    placeholder="Forbes"
                                />

                                <MediaUploadCheck>
                                    <MediaUpload
                                        onSelect={(media) => onSelectLogo(index, media)}
                                        allowedTypes={['image']}
                                        value={logo.id}
                                        render={({ open }) => (
                                            <div style={{ marginBottom: '10px' }}>
                                                <label className="components-base-control__label" style={{ display: 'block', marginBottom: '4px' }}>
                                                    {__('Or Upload Image', 'author-website-templates')}
                                                </label>
                                                {logo.url ? (
                                                    <div style={{ display: 'flex', gap: '5px' }}>
                                                        <Button onClick={open} variant="secondary" size="small" style={{ flex: 1 }}>
                                                            {__('Replace', 'author-website-templates')}
                                                        </Button>
                                                        <Button
                                                            onClick={() => updateLogo(index, 'url', '')}
                                                            variant="secondary"
                                                            isDestructive
                                                            size="small"
                                                        >
                                                            {__('X', 'author-website-templates')}
                                                        </Button>
                                                    </div>
                                                ) : (
                                                    <Button onClick={open} variant="secondary" size="small" style={{ width: '100%' }}>
                                                        {__('Upload Image', 'author-website-templates')}
                                                    </Button>
                                                )}
                                            </div>
                                        )}
                                    />
                                </MediaUploadCheck>

                                <TextControl
                                    label={__('Link URL', 'author-website-templates')}
                                    value={logo.link}
                                    onChange={(value) => updateLogo(index, 'link', value)}
                                    placeholder="#"
                                />

                                <Button
                                    onClick={() => removeLogo(index)}
                                    isDestructive
                                    variant="link"
                                    size="small"
                                >
                                    {__('Remove Logo', 'author-website-templates')}
                                </Button>
                            </div>
                        ))}
                    </div>

                    <ProLock isLocked={!isPro}>
                        <Button
                            onClick={isPro ? addLogo : undefined}
                            variant="primary"
                            disabled={!isPro}
                            style={{ width: '100%', justifyContent: 'center' }}
                        >
                            {__('Add New Logo', 'author-website-templates')}
                        </Button>
                    </ProLock>
                </PanelBody>
            </InspectorControls>

            {/* STYLES TAB */}
            <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={200}
                        initialPosition={32}
                    />
                    <RangeControl
                        label={__('Bottom Padding (px)', 'author-website-templates')}
                        value={paddingBottom}
                        onChange={(value) => setAttributes({ paddingBottom: value })}
                        min={0}
                        max={200}
                        initialPosition={32}
                    />
                </PanelBody>

                <ProLock isLocked={!isPro}>
                    <PanelColorSettings
                        title={__('Colors', 'author-website-templates')}
                        initialOpen={true}
                        colorSettings={[
                            {
                                value: bgColor === 'bg-primary' ? '' : bgColor,
                                onChange: (value) => setAttributes({ bgColor: value }),
                                label: __('Background Color', 'author-website-templates'),
                            }
                        ]}
                    />
                </ProLock>
            </InspectorControls>

            <div className="awt-editor-preview">

                <ServerSideRender
                    block="awt/author-pro-featured-in"
                    attributes={attributes}
                />
            </div>
        </div>
    );
}
