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

/**
 * ProLock Component - Wrapper for Pro-only controls
 * Renders children normally if Pro, otherwise shows locked/grayed controls with upgrade link
 */
const ProLock = ({ isPro, children }) => {
    if (isPro) return children;

    return (
        <div className="pro-lock-wrapper" style={{ position: 'relative', cursor: 'not-allowed' }}>
            {/* The actual controls (Blurred & Disabled) */}
            <div style={{ opacity: 0.4, pointerEvents: 'none', filter: 'grayscale(100%)' }}>
                {children}
            </div>

            {/* The Overlay (Clickable) */}
            <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: 10,
                    cursor: 'pointer'
                }}
                aria-label="Upgrade to Pro"
            >
                <Tooltip text="🔒 Pro Feature - Click to Upgrade">
                    {/* Invisible div to catch hover/click */}
                    <div style={{ width: '100%', height: '100%' }} />
                </Tooltip>
            </a>
        </div>
    );
};

export default function Edit({ attributes, setAttributes, clientId }) {
    const {
        blockId,
        badgeText,
        title,
        description,
        contactDetails,
        submitButtonText,
        useShortcode,
        customShortcode,
        sectionBgColor,
        formBgColor,
        accentColor,
        primaryColor,
        textColor
    } = attributes;

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

    // Set blockId if empty
    useEffect(() => {
        if (!blockId) {
            setAttributes({ blockId: clientId });
        }
    }, [blockId, clientId, setAttributes]);

    // Handle updating contact details
    const updateContactDetail = (index, key, value) => {
        const newDetails = [...contactDetails];
        newDetails[index][key] = value;
        setAttributes({ contactDetails: newDetails });
    };

    const addContactDetail = () => {
        setAttributes({
            contactDetails: [
                ...contactDetails,
                { icon: 'fas fa-info-circle', title: 'Title', text: 'Detail Text' }
            ]
        });
    };

    const removeContactDetail = (index) => {
        const newDetails = contactDetails.filter((_, i) => i !== index);
        setAttributes({ contactDetails: newDetails });
    };

    // Styling
    const wrapperStyle = {
        backgroundColor: sectionBgColor,
    };

    const badgeStyle = {
        color: accentColor,
    };

    const titleStyle = {
        color: primaryColor
    };

    const descStyle = {
        color: textColor
    };

    const iconBoxStyle = {
        backgroundColor: formBgColor, // reusing paper bg for icon box
        color: accentColor
    };

    const headingStyle = {
        color: primaryColor
    };

    const detailTextStyle = {
        color: textColor // usually secondary but mapping to textColor for simplicity
    };

    const formStyle = {
        backgroundColor: formBgColor
    };

    const labelStyle = {
        color: primaryColor
    };

    const btnStyle = {
        backgroundColor: primaryColor,
        color: '#ffffff'
    };

    const blockProps = useBlockProps({
        className: `block-${blockId}`,
        style: wrapperStyle
    });

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    <TextControl
                        label={__('Badge Text', 'author-website-templates')}
                        value={badgeText}
                        onChange={(value) => setAttributes({ badgeText: value })}
                    />
                    <TextareaControl
                        label={__('Title', 'author-website-templates')}
                        value={title}
                        onChange={(value) => setAttributes({ title: value })}
                    />
                    <TextareaControl
                        label={__('Description', 'author-website-templates')}
                        value={description}
                        onChange={(value) => setAttributes({ description: value })}
                    />

                    <hr className="my-4" />

                    <h4 className="font-bold mb-2">{__('Contact Details', 'author-website-templates')}</h4>
                    {contactDetails.map((item, index) => (
                        <div key={index} className="mb-4 p-3 border rounded bg-white">
                            <TextControl
                                label={__('Icon Class (FontAwesome)', 'author-website-templates')}
                                value={item.icon}
                                onChange={(value) => updateContactDetail(index, 'icon', value)}
                                help={__('e.g., fas fa-envelope', 'author-website-templates')}
                            />
                            <TextControl
                                label={__('Title', 'author-website-templates')}
                                value={item.title}
                                onChange={(value) => updateContactDetail(index, 'title', value)}
                            />
                            <TextControl
                                label={__('Text', 'author-website-templates')}
                                value={item.text}
                                onChange={(value) => updateContactDetail(index, 'text', value)}
                            />
                            <Button
                                isDestructive
                                variant="link"
                                onClick={() => removeContactDetail(index)}
                            >
                                {__('Remove Item', 'author-website-templates')}
                            </Button>
                        </div>
                    ))}
                    <Button variant="secondary" onClick={addContactDetail} className="w-full">
                        {__('Add Contact Detail', 'author-website-templates')}
                    </Button>

                    <hr className="my-4" />

                    <h4 className="font-bold mb-2">{__('Form Settings', 'author-website-templates')}</h4>
                    <ToggleControl
                        label={__('Use Custom Shortcode', 'author-website-templates')}
                        checked={useShortcode}
                        onChange={(value) => setAttributes({ useShortcode: value })}
                    />

                    {useShortcode ? (
                        <TextareaControl
                            label={__('Custom Shortcode', 'author-website-templates')}
                            value={customShortcode}
                            onChange={(value) => setAttributes({ customShortcode: value })}
                            placeholder="[contact-form-7 id='123']"
                        />
                    ) : (
                        <TextControl
                            label={__('Submit Button Text', 'author-website-templates')}
                            value={submitButtonText}
                            onChange={(value) => setAttributes({ submitButtonText: value })}
                        />
                    )}
                </PanelBody>

                <PanelBody title={__('Design Settings', 'author-website-templates')}>
                    {!isPro && (
                        <Notice status="warning" isDismissible={false}>
                            {__('🔒 Upgrade to Pro to unlock styling controls', 'author-website-templates')}
                        </Notice>
                    )}
                    <ProLock isPro={isPro}>
                        <PanelColorSettings
                            title={__('Colors', 'author-website-templates')}
                            colorSettings={[
                                {
                                    value: sectionBgColor,
                                    onChange: (color) => setAttributes({ sectionBgColor: color }),
                                    label: __('Section Background', 'author-website-templates'),
                                },
                                {
                                    value: formBgColor,
                                    onChange: (color) => setAttributes({ formBgColor: color }),
                                    label: __('Form Background', 'author-website-templates'),
                                },
                                {
                                    value: accentColor,
                                    onChange: (color) => setAttributes({ accentColor: color }),
                                    label: __('Accent Color (Icons/Badge)', 'author-website-templates'),
                                },
                                {
                                    value: primaryColor,
                                    onChange: (color) => setAttributes({ primaryColor: color }),
                                    label: __('Primary Color (Headings)', 'author-website-templates'),
                                },
                                {
                                    value: textColor,
                                    onChange: (color) => setAttributes({ textColor: color }),
                                    label: __('Text Color', 'author-website-templates'),
                                },
                            ]}
                        />
                    </ProLock>
                </PanelBody>
            </InspectorControls>

            <section {...blockProps}>
                <div className="py-24 awt-container">
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-16">
                        {/* Left Column */}
                        <div>
                            <RichText
                                tagName="span"
                                className="text-accent font-bold text-xs uppercase tracking-widest block mb-2"
                                value={badgeText}
                                onChange={(value) => setAttributes({ badgeText: value })}
                                style={badgeStyle}
                                placeholder={__('Badge...', 'author-website-templates')}
                            />
                            <RichText
                                tagName="h2"
                                className="text-4xl font-serif font-bold text-primary mt-2 mb-6"
                                value={title}
                                onChange={(value) => setAttributes({ title: value })}
                                style={titleStyle}
                                placeholder={__('Title...', 'author-website-templates')}
                            />
                            <RichText
                                tagName="p"
                                className="text-secondary mb-8 leading-relaxed"
                                value={description}
                                onChange={(value) => setAttributes({ description: value })}
                                style={descStyle}
                                placeholder={__('Description...', 'author-website-templates')}
                            />

                            <div className="space-y-6">
                                {contactDetails.map((item, index) => (
                                    <div key={index} className="flex items-start gap-4 group">
                                        <MediaUploadCheck>
                                            <MediaUpload
                                                onSelect={(media) => {
                                                    const newDetails = [...contactDetails];
                                                    newDetails[index].iconId = media.id;
                                                    newDetails[index].iconUrl = media.url;
                                                    setAttributes({ contactDetails: newDetails });
                                                }}
                                                allowedTypes={['image']}
                                                value={item.iconId}
                                                render={({ open }) => (
                                                    <div
                                                        onClick={open}
                                                        className={`w-10 h-10 rounded flex items-center justify-center relative overflow-hidden cursor-pointer transition hover:opacity-80 ${formBgColor ? '' : 'bg-paper'} ${accentColor ? '' : 'text-accent'}`}
                                                        style={iconBoxStyle}
                                                    >
                                                        {item.iconUrl ? (
                                                            <img src={item.iconUrl} alt={item.title} className="w-5 h-5 object-contain" />
                                                        ) : (
                                                            <span className="w-5 h-5 flex items-center justify-center" dangerouslySetInnerHTML={{ __html: item.svgContent }} />
                                                        )}
                                                    </div>
                                                )}
                                            />
                                        </MediaUploadCheck>
                                        <div>
                                            <RichText
                                                tagName="h4"
                                                className={`font-bold m-0 ${primaryColor ? '' : 'text-primary'}`}
                                                value={item.title}
                                                onChange={(value) => updateContactDetail(index, 'title', value)}
                                                style={headingStyle}
                                            />
                                            <RichText
                                                tagName="p"
                                                className={`text-sm m-0 ${textColor ? '' : 'text-secondary'}`}
                                                value={item.text}
                                                onChange={(value) => updateContactDetail(index, 'text', value)}
                                                style={detailTextStyle}
                                            />
                                        </div>
                                    </div>
                                ))}
                                {/* Add New Item Button (Canvas) */}
                                <div
                                    role="button"
                                    onClick={addContactDetail}
                                    className={`mt-4 border-2 border-dashed border-gray-300 rounded-lg p-4 flex items-center justify-center text-gray-400 hover:text-primary hover:border-primary cursor-pointer transition ${!isPro ? 'opacity-50 cursor-not-allowed' : ''}`}
                                >
                                    <span className="text-sm font-bold">+ Add Contact Detail</span>
                                </div>
                            </div>
                        </div>

                        {/* Right Column - Form */}
                        {useShortcode ? (
                            <div className="bg-paper p-8 rounded-2xl border border-gray-100 shadow-sm flex items-center justify-center text-center" style={formStyle}>
                                <div>
                                    <h4 className="font-bold mb-2">Shortcode Preview</h4>
                                    <code className="bg-gray-200 px-2 py-1 rounded block mb-2">{customShortcode || 'No shortcode entered'}</code>
                                    <p className="text-sm text-gray-500">The form will be rendered here on the frontend.</p>
                                </div>
                            </div>
                        ) : (
                            <form className={`p-8 rounded-2xl border border-gray-100 shadow-sm ${formBgColor ? '' : 'bg-paper'}`} style={formStyle} onSubmit={(e) => e.preventDefault()}>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                                    <div>
                                        <label className={`block text-xs font-bold uppercase mb-2 ${primaryColor ? '' : 'text-primary'}`} style={labelStyle}>Name</label>
                                        <input type="text"
                                            className="w-full px-4 py-3 rounded bg-white border border-gray-200 focus:outline-none focus:border-accent"
                                            placeholder="Your Name" disabled />
                                    </div>
                                    <div>
                                        <label className={`block text-xs font-bold uppercase mb-2 ${primaryColor ? '' : 'text-primary'}`} style={labelStyle}>Email</label>
                                        <input type="email"
                                            className="w-full px-4 py-3 rounded bg-white border border-gray-200 focus:outline-none focus:border-accent"
                                            placeholder="Your Email" disabled />
                                    </div>
                                </div>
                                <div className="mb-6">
                                    <label className={`block text-xs font-bold uppercase mb-2 ${primaryColor ? '' : 'text-primary'}`} style={labelStyle}>Subject</label>
                                    <input type="text"
                                        className="w-full px-4 py-3 rounded bg-white border border-gray-200 focus:outline-none focus:border-accent"
                                        placeholder="Speaking / General Inquiry" disabled />
                                </div>
                                <div className="mb-6">
                                    <label className={`block text-xs font-bold uppercase mb-2 ${primaryColor ? '' : 'text-primary'}`} style={labelStyle}>Message</label>
                                    <textarea rows="4"
                                        className="w-full px-4 py-3 rounded bg-white border border-gray-200 focus:outline-none focus:border-accent"
                                        placeholder="How can we help?" disabled></textarea>
                                </div>
                                <button className={`w-full py-4 font-bold rounded transition ${primaryColor ? '' : 'bg-primary'} ${accentColor ? '' : 'hover:bg-accent'} text-white`} style={btnStyle}>
                                    {submitButtonText}
                                </button>
                            </form>
                        )}
                    </div>
                </div>
            </section>
        </>
    );
}
