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

/**
 * ProLock Component - Wrapper for Pro-only controls
 */
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,
        badgeText,
        title,
        description,
        authorImageId,
        authorImageUrl,
        authorImageAlt,
        features,
        btnText,
        btnUrl,
        paddingTop,
        paddingBottom,
        bgColor,
        accentColor,
        btnBgColor,
        btnTextColor,
        btnBorderColor,
        btnHoverBgColor,
        btnHoverTextColor,

        btnHoverBorderColor,
        anchor
    } = attributes;

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

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

    // Determine Selector ID
    const cssSelectorId = anchor ? anchor : blockId;

    // Generate Dynamic CSS for Editor
    const dynamicStyles = `
        #${cssSelectorId} .awt-accent { color: ${accentColor} !important; }
        #${cssSelectorId} .awt-accent svg { color: ${accentColor} !important; }
        #${cssSelectorId} .awt-btn {
            background-color: ${btnBgColor};
            color: ${btnTextColor};
            border-color: ${btnBorderColor};
        }
        #${cssSelectorId} .awt-btn:hover {
            background-color: ${btnHoverBgColor};
            color: ${btnHoverTextColor};
            border-color: ${btnHoverBorderColor};
        }
    `;

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

    // Features Logic
    const updateFeature = (index, value) => {
        const newFeatures = [...features];
        newFeatures[index] = value;
        setAttributes({ features: newFeatures });
    };

    const addFeature = () => {
        setAttributes({ features: [...features, 'New Feature'] });
    };

    const removeFeature = (index) => {
        const newFeatures = features.filter((_, i) => i !== index);
        setAttributes({ features: newFeatures });
    };

    // Helper to conditionally apply classes
    const getBtnClasses = () => {
        let classes = 'awt-btn inline-block px-8 py-3 border font-bold rounded transition';
        if (!btnTextColor) classes += ' text-primary';
        if (!btnBorderColor) classes += ' border-primary';
        // Only apply default hover classes if no custom hover colors are set
        if (!btnHoverBgColor) classes += ' hover:bg-slate-900';
        if (!btnHoverTextColor) classes += ' hover:text-white';
        return classes;
    };

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

            <InspectorControls>
                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    <TextControl
                        label={__('Badge Text', 'author-website-templates')}
                        value={badgeText}
                        onChange={(value) => setAttributes({ badgeText: value })}
                    />
                    <TextControl
                        label={__('Button URL', 'author-website-templates')}
                        value={btnUrl}
                        onChange={(value) => setAttributes({ btnUrl: value })}
                    />
                    <TextControl
                        label={__('Author Image Alt Text', 'author-website-templates')}
                        value={authorImageAlt}
                        onChange={(value) => setAttributes({ authorImageAlt: value })}
                    />
                    <hr className="my-4" />

                    <p><strong>{__('Features List', 'author-website-templates')}</strong></p>
                    {features.map((feature, index) => (
                        <div key={index} className="flex gap-2 mb-2 items-center">
                            <TextControl
                                value={feature}
                                onChange={(value) => updateFeature(index, value)}
                                className="mb-0 flex-grow"
                            />
                            <Button
                                isDestructive
                                icon="minus"
                                onClick={() => removeFeature(index)}
                                label={__('Remove', 'author-website-templates')}
                            />
                        </div>
                    ))}

                    <ProLock isLocked={!isPro}>
                        <Button variant="secondary" onClick={addFeature} className="w-full justify-center mt-2">
                            {__('Add New Feature', 'author-website-templates')}
                        </Button>
                    </ProLock>
                </PanelBody>

                <PanelBody title={__('Spacing', 'author-website-templates')} initialOpen={false}>
                    <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>
            </InspectorControls>

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

                    <PanelColorSettings
                        title={__('Accent & Icon Color', 'author-website-templates')}
                        initialOpen={false}
                        colorSettings={[
                            {
                                value: accentColor,
                                onChange: (value) => setAttributes({ accentColor: value }),
                                label: __('Accent Color', 'author-website-templates'),
                            }
                        ]}
                    />

                    <PanelColorSettings
                        title={__('Button Colors (Normal)', 'author-website-templates')}
                        initialOpen={false}
                        colorSettings={[
                            {
                                value: btnTextColor,
                                onChange: (value) => setAttributes({ btnTextColor: value }),
                                label: __('Text Color', 'author-website-templates'),
                            },
                            {
                                value: btnBgColor,
                                onChange: (value) => setAttributes({ btnBgColor: value }),
                                label: __('Background Color', 'author-website-templates'),
                            },
                            {
                                value: btnBorderColor,
                                onChange: (value) => setAttributes({ btnBorderColor: value }),
                                label: __('Border Color', 'author-website-templates'),
                            }
                        ]}
                    />

                    <PanelColorSettings
                        title={__('Button Colors (Hover)', 'author-website-templates')}
                        initialOpen={false}
                        colorSettings={[
                            {
                                value: btnHoverTextColor,
                                onChange: (value) => setAttributes({ btnHoverTextColor: value }),
                                label: __('Hover Text', 'author-website-templates'),
                            },
                            {
                                value: btnHoverBgColor,
                                onChange: (value) => setAttributes({ btnHoverBgColor: value }),
                                label: __('Hover Background', 'author-website-templates'),
                            },
                            {
                                value: btnHoverBorderColor,
                                onChange: (value) => setAttributes({ btnHoverBorderColor: value }),
                                label: __('Hover Border', 'author-website-templates'),
                            }
                        ]}
                    />
                </ProLock>
            </InspectorControls>

            {/* Editor Canvas Visuals */}
            <div className={`awt-container mx-auto ${bgColor && bgColor.includes('bg-') ? bgColor : ''}`}>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-16 items-center">

                    {/* Left Column: Images */}
                    <div className="relative pl-6 pt-6">
                        <div className="awt-border-accent absolute top-0 left-0 w-full h-full border-2 border-accent/20 rounded-2xl -z-10"></div>
                        <MediaUploadCheck>
                            <MediaUpload
                                onSelect={(media) => setAttributes({ authorImageUrl: media.url, authorImageId: media.id })}
                                allowedTypes={['image']}
                                value={authorImageId}
                                render={({ open }) => (
                                    <div onClick={open} className="cursor-pointer group">
                                        {authorImageUrl ? (
                                            <img
                                                src={authorImageUrl}
                                                alt={authorImageAlt}
                                                className="rounded-xl shadow-xl w-full h-[500px] object-cover grayscale hover:grayscale-0 transition duration-500"
                                            />
                                        ) : (
                                            <div className="w-full h-[500px] bg-gray-100 rounded-xl flex items-center justify-center text-gray-400 border-2 border-dashed border-gray-300">
                                                {__('Select Author Image', 'author-website-templates')}
                                            </div>
                                        )}
                                    </div>
                                )}
                            />
                        </MediaUploadCheck>
                    </div>

                    {/* Right Column: Content */}
                    <div>
                        <RichText
                            tagName="span"
                            className="awt-accent text-accent font-bold text-xs uppercase tracking-widest mb-2 block"
                            value={badgeText}
                            onChange={(value) => setAttributes({ badgeText: value })}
                            placeholder={__('Badge Text...', 'author-website-templates')}
                        />

                        <RichText
                            tagName="h2"
                            className="text-4xl font-serif font-bold text-primary mb-6"
                            value={title}
                            onChange={(value) => setAttributes({ title: value })}
                            placeholder={__('Heading...', 'author-website-templates')}
                        />

                        <RichText
                            tagName="div"
                            className="text-secondary leading-relaxed mb-6"
                            value={description}
                            onChange={(value) => setAttributes({ description: value })}
                            placeholder={__('Write description...', 'author-website-templates')}
                        />

                        {/* Feature List Visuals */}
                        <ul className="space-y-4 mb-8">
                            {features.map((feature, index) => (
                                <li key={index} className="flex items-center gap-3 text-primary font-medium">
                                    <span className="awt-accent">
                                        <svg className="w-6 h-6 text-accent" fill="currentColor" viewBox="0 0 512 512">
                                            <path d="M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z" />
                                        </svg>
                                    </span>
                                    <RichText
                                        tagName="span"
                                        value={feature}
                                        onChange={(value) => updateFeature(index, value)}
                                        placeholder={__('Feature text...', 'author-website-templates')}
                                        // Handle "Enter" to add new line, "Backspace" to remove empty
                                        onKeyDown={(e) => {
                                            if (e.key === 'Enter') {
                                                e.preventDefault();
                                                const newFeatures = [...features];
                                                newFeatures.splice(index + 1, 0, ''); // Insert empty string after current
                                                setAttributes({ features: newFeatures });
                                            } else if (e.key === 'Backspace' && feature === '' && features.length > 1) {
                                                e.preventDefault();
                                                removeFeature(index);
                                            }
                                        }}
                                    />
                                </li>
                            ))}
                        </ul>

                        {/* Button Visual */}
                        <a
                            href="#"
                            onClick={(e) => e.preventDefault()}
                            className={getBtnClasses()}
                        >
                            <RichText
                                tagName="span"
                                value={btnText}
                                onChange={(value) => setAttributes({ btnText: value })}
                                placeholder={__('Button Text', 'author-website-templates')}
                                allowedFormats={[]} // Disable bold/italic inside button
                            />
                        </a>
                    </div>
                </div>
            </div>
        </div>
    );
}