import { useBlockProps, RichText, MediaUpload, MediaUploadCheck, InspectorControls } from '@wordpress/block-editor';
import { PanelBody, Button, SelectControl, TextControl, ToggleControl, TextareaControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { link as linkIcon } from '@wordpress/icons';
import { useEffect } from '@wordpress/element';

export default function Edit({ attributes, setAttributes, context }) {
    const { imageId, imageUrl, title, description, hoverEffect, cardUrl, openInNewTab, cardStyle, iconSvg } = attributes;

    const isFun = cardStyle === 'fun';
    const isElegant = cardStyle === 'elegant';

    // Sync context style to attribute
    useEffect(() => {
        if (context['awt/activityStyle'] && context['awt/activityStyle'] !== cardStyle) {
            setAttributes({ cardStyle: context['awt/activityStyle'] });
        }
    }, [context['awt/activityStyle'], cardStyle, setAttributes]);

    // Map hover effect to Tailwind class
    const getHoverClass = () => {
        switch (hoverEffect) {
            case 'rotate-left':
                return 'hover:rotate-[-2deg]';
            case 'rotate-right':
                return 'hover:rotate-[2deg]';
            case 'scale':
            default:
                return 'hover:scale-105';
        }
    };

    const onSelectImage = (media) => {
        setAttributes({
            imageId: media.id,
            imageUrl: media.url,
        });
    };

    const blockProps = useBlockProps({
        className: isElegant
            ? `block bg-white p-8 rounded-lg shadow-sm border border-gray-100 text-center group hover:shadow-lg transition-all duration-300 ${cardUrl ? 'cursor-pointer' : ''}`
            : `block bg-white p-8 rounded-xl shadow-lg transition-all duration-300 hover:shadow-2xl ${getHoverClass()} ${cardUrl ? 'cursor-pointer' : ''}`
    });

    // Typography Classes
    const titleClass = isElegant
        ? 'text-xl font-serif font-bold text-brand-dark mb-3'
        : 'text-2xl font-black text-center text-navy mb-2';

    const descClass = isElegant
        ? 'text-brand-gray text-sm leading-relaxed'
        : 'text-center text-navy/70';

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Activity Card Settings', 'author-website-templates')} initialOpen={true}>
                    {isFun ? (
                        <>
                            {/* Image Upload */}
                            <div className="sidebar-image-control" style={{ marginBottom: '16px' }}>
                                <p style={{ marginBottom: '8px', fontWeight: '600' }}>
                                    {__('Activity Image', 'author-website-templates')}
                                </p>
                                <MediaUploadCheck>
                                    <MediaUpload
                                        onSelect={onSelectImage}
                                        allowedTypes={['image']}
                                        value={imageId}
                                        render={({ open }) => (
                                            <>
                                                {imageUrl ? (
                                                    <>
                                                        <img
                                                            src={imageUrl}
                                                            alt={title}
                                                            style={{
                                                                width: '100%',
                                                                height: 'auto',
                                                                marginBottom: '10px',
                                                                borderRadius: '8px'
                                                            }}
                                                        />
                                                        <Button
                                                            variant="secondary"
                                                            onClick={open}
                                                            style={{ width: '100%', marginBottom: '8px' }}
                                                        >
                                                            {__('Replace Image', 'author-website-templates')}
                                                        </Button>
                                                        <Button
                                                            variant="link"
                                                            isDestructive
                                                            onClick={() => setAttributes({ imageId: 0, imageUrl: '' })}
                                                        >
                                                            {__('Remove', 'author-website-templates')}
                                                        </Button>
                                                    </>
                                                ) : (
                                                    <Button variant="primary" onClick={open} style={{ width: '100%' }}>
                                                        {__('Upload Image', 'author-website-templates')}
                                                    </Button>
                                                )}
                                            </>
                                        )}
                                    />
                                </MediaUploadCheck>
                            </div>

                            {/* Hover Effect Selection */}
                            <SelectControl
                                label={__('Hover Effect', 'author-website-templates')}
                                value={hoverEffect}
                                options={[
                                    { label: __('Rotate Left (-2deg)', 'author-website-templates'), value: 'rotate-left' },
                                    { label: __('Scale (1.05x)', 'author-website-templates'), value: 'scale' },
                                    { label: __('Rotate Right (2deg)', 'author-website-templates'), value: 'rotate-right' },
                                ]}
                                onChange={(value) => setAttributes({ hoverEffect: value })}
                                help={__('Choose the hover animation for this card', 'author-website-templates')}
                            />
                        </>
                    ) : (
                        <TextareaControl
                            label={__('SVG Icon Code', 'author-website-templates')}
                            value={iconSvg}
                            onChange={(value) => setAttributes({ iconSvg: value })}
                            help={__('Paste raw SVG code here (e.g. from Heroicons)', 'author-website-templates')}
                            rows={5}
                        />
                    )}
                </PanelBody>

                {/* Link Settings Panel */}
                <PanelBody title={__('Link Settings', 'author-website-templates')} initialOpen={false}>
                    <TextControl
                        label={__('Card URL (Optional)', 'author-website-templates')}
                        value={cardUrl}
                        onChange={(value) => setAttributes({ cardUrl: value })}
                        placeholder="https://example.com"
                        help={__('If provided, the entire card becomes a clickable link', 'author-website-templates')}
                        type="url"
                    />

                    {cardUrl && (
                        <ToggleControl
                            label={__('Open in New Tab', 'author-website-templates')}
                            checked={openInNewTab}
                            onChange={(value) => setAttributes({ openInNewTab: value })}
                        />
                    )}
                </PanelBody>
            </InspectorControls>

            <div {...blockProps}>
                {/* Link Indicator */}
                {cardUrl && (
                    <div
                        style={{
                            position: 'absolute',
                            top: '10px',
                            right: '10px',
                            background: '#0073aa',
                            color: 'white',
                            borderRadius: '4px',
                            padding: '4px 8px',
                            fontSize: '11px',
                            fontWeight: 'bold',
                            display: 'flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                    >
                        <span>🔗</span>
                        {openInNewTab ? '↗' : '→'}
                    </div>
                )}

                {/* Visual Media */}
                {isFun ? (
                    <MediaUploadCheck>
                        <MediaUpload
                            onSelect={onSelectImage}
                            allowedTypes={['image']}
                            value={imageId}
                            render={({ open }) => (
                                <div className="mx-auto mb-4 cursor-pointer" onClick={open}>
                                    {imageUrl ? (
                                        <img src={imageUrl} alt={title} className="mx-auto" />
                                    ) : (
                                        <div className="bg-gray-200 w-24 h-24 mx-auto flex items-center justify-center rounded">
                                            <Button variant="primary" onClick={open}>
                                                {__('Upload', 'author-website-templates')}
                                            </Button>
                                        </div>
                                    )}
                                </div>
                            )}
                        />
                    </MediaUploadCheck>
                ) : (
                    <div
                        className="w-16 h-16 bg-gray-200 rounded-full flex items-center justify-center mx-auto mb-6 text-brand-dark group-hover:bg-brand-dark group-hover:text-white transition-colors"
                        dangerouslySetInnerHTML={{ __html: iconSvg || '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>' }}
                    />
                )}

                {/* Title */}
                <RichText
                    tagName="h3"
                    className={titleClass}
                    value={title}
                    onChange={(value) => setAttributes({ title: value })}
                    placeholder={__('Activity title...', 'author-website-templates')}
                />

                {/* Description */}
                <RichText
                    tagName="p"
                    className={descClass}
                    value={description}
                    onChange={(value) => setAttributes({ description: value })}
                    placeholder={__('Activity description...', 'author-website-templates')}
                />
            </div>
        </>
    );
}
