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

// ProLock Component
const ProLock = ({ isPro, children }) => {
    if (isPro) return children;
    return (
        <div className="pro-lock-wrapper" style={{ position: 'relative', cursor: 'not-allowed' }}>
            <div style={{ opacity: 0.4, pointerEvents: 'none', filter: 'grayscale(100%)' }}>{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: 10, cursor: 'pointer' }} aria-label="Upgrade to Pro">
                <Tooltip text="🔒 Pro Feature - Click to Upgrade"><div style={{ width: '100%', height: '100%' }} /></Tooltip>
            </a>
        </div>
    );
};

export default function Edit({ attributes, setAttributes, clientId }) {
    const { heading, images, columns, sectionBgColor, headingColor, blockId } = attributes;
    const isPro = window.awtVars?.isPro || false;

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

    const headingClass = headingColor ? 'text-4xl md:text-5xl font-black text-center mb-12' : 'text-4xl md:text-5xl font-black text-navy text-center mb-12';
    const containerClass = sectionBgColor ? 'py-24' : 'py-24';

    const blockProps = useBlockProps({
        className: `alignfull block-${blockId} ${containerClass}`,
        style: {
            backgroundColor: sectionBgColor || undefined,
        }
    });

    const onSelectImages = (media) => {
        const selectedImages = media.map((item) => ({
            id: item.id,
            url: item.url,
            alt: item.alt || '',
        }));
        setAttributes({ images: selectedImages });
    };

    const removeImage = (indexToRemove) => {
        const newImages = images.filter((_, index) => index !== indexToRemove);
        setAttributes({ images: newImages });
    };

    // Grid columns class
    const gridClass = `grid grid-cols-2 md:grid-cols-${columns} gap-4 md:gap-6`;

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    <RichText
                        tagName="div"
                        value={heading}
                        onChange={(value) => setAttributes({ heading: value })}
                        placeholder={__('Gallery heading...', 'author-website-templates')}
                        style={{ marginBottom: '16px' }}
                    />

                    <RangeControl
                        label={__('Columns (Desktop)', 'author-website-templates')}
                        value={columns}
                        onChange={(value) => setAttributes({ columns: value })}
                        min={2}
                        max={6}
                        step={1}
                        help={__('Number of columns on desktop screens', 'author-website-templates')}
                    />

                    {images.length > 0 && (
                        <MediaUploadCheck>
                            <MediaUpload
                                onSelect={onSelectImages}
                                allowedTypes={['image']}
                                value={images.map(img => img.id)}
                                multiple={true}
                                gallery={true}
                                render={({ open }) => (
                                    <Button variant="secondary" onClick={open} style={{ width: '100%', marginTop: '8px' }}>
                                        {__('Edit Gallery', 'author-website-templates')}
                                    </Button>
                                )}
                            />
                        </MediaUploadCheck>
                    )}
                </PanelBody>

                <PanelBody title={__('Design Settings', 'author-website-templates')} initialOpen={false}>
                    {!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: headingColor,
                                    onChange: (color) => setAttributes({ headingColor: color }),
                                    label: __('Heading Color', 'author-website-templates'),
                                },
                            ]}
                        />
                    </ProLock>
                </PanelBody>
            </InspectorControls>

            <section {...blockProps}>
                <div className="awt-container mx-auto px-6">
                    <RichText
                        tagName="h2"
                        className={headingClass}
                        value={heading}
                        onChange={(value) => setAttributes({ heading: value })}
                        placeholder={__('Gallery heading...', 'author-website-templates')}
                        style={{ color: headingColor || undefined }}
                    />

                    {images.length === 0 ? (
                        <div className="text-center py-20 bg-gray-100 rounded-lg">
                            <MediaUploadCheck>
                                <MediaUpload
                                    onSelect={onSelectImages}
                                    allowedTypes={['image']}
                                    value={images.map(img => img.id)}
                                    multiple={true}
                                    gallery={true}
                                    render={({ open }) => (
                                        <div>
                                            <p className="text-gray-500 mb-4">{__('No photos yet', 'author-website-templates')}</p>
                                            <Button variant="primary" onClick={open} size="large">
                                                {__('📸 Upload Photos', 'author-website-templates')}
                                            </Button>
                                        </div>
                                    )}
                                />
                            </MediaUploadCheck>
                        </div>
                    ) : (
                        <div className={gridClass}>
                            {images.map((image, index) => {
                                const rotationClass = index % 2 === 0 ? 'hover:rotate-2' : 'hover:-rotate-2';
                                return (
                                    <div key={image.id || index} className="relative overflow-hidden rounded-lg shadow-lg group">
                                        <img
                                            src={image.url}
                                            alt={image.alt}
                                            className={`w-full h-full aspect-square object-cover transition-all duration-300 hover:shadow-2xl hover:scale-105 ${rotationClass}`}
                                        />
                                        <button
                                            onClick={() => removeImage(index)}
                                            className="absolute top-2 right-2 bg-red-500 text-white rounded-full w-8 h-8 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                                            aria-label={__('Remove image', 'author-website-templates')}
                                        >
                                            ×
                                        </button>
                                    </div>
                                );
                            })}
                        </div>
                    )}
                </div>
            </section>
        </>
    );
}
