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

/**
 * 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.6 }}>
            <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: '8px 16px',
                    borderRadius: '4px',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                    fontWeight: '500',
                    fontSize: '13px',
                    color: '#333',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px'
                }}>
                    <span role="img" aria-label="lock">🔒</span> {__('Upgrade to Pro', 'author-website-templates')}
                </div>
            </a>
        </div>
    );
};

export default function Edit({ attributes, setAttributes, clientId }) {
    const {
        blockId,
        anchor,
        badgeText,
        title,
        subtitle,
        description,
        bookImageId,
        bookImageUrl,
        storeButtons,
        showFloatingCard,
        floatingCardTopLabel,
        floatingCardMainLabel,
        floatingCardUrl,
        ratingStars,
        ratingValue,
        ratingText,
        bgColor,
        shapeColor,
        accentColor,
        borderColor,
        paddingTop,
        paddingBottom
    } = attributes;

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

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

    const blockProps = useBlockProps({
        className: 'awt-author-pro-hero relative overflow-hidden',
        id: anchor || blockId,
        style: {
            backgroundColor: bgColor || undefined,
            paddingTop: paddingTop ? `${paddingTop}px` : undefined,
            paddingBottom: paddingBottom ? `${paddingBottom}px` : undefined,
        }
    });

    // Handle store button changes
    const updateStoreButton = (index, field, value) => {
        const newButtons = [...storeButtons];
        newButtons[index] = { ...newButtons[index], [field]: value };

        // If updating iconKey, also update iconSvg
        if (field === 'iconKey' && SOCIAL_ICONS[value]) {
            newButtons[index].iconSvg = SOCIAL_ICONS[value].path;
        }

        setAttributes({ storeButtons: newButtons });
    };

    const addStoreButton = () => {
        setAttributes({
            storeButtons: [
                ...storeButtons,
                {
                    id: `store-${Date.now()}`,
                    iconKey: 'amazon',
                    iconSvg: SOCIAL_ICONS['amazon'].path,
                    iconImageUrl: '',
                    topLabel: 'Buy On',
                    mainLabel: 'Amazon',
                    url: '#'
                }
            ]
        });
    };

    const removeStoreButton = (index) => {
        const newButtons = storeButtons.filter((_, i) => i !== index);
        setAttributes({ storeButtons: newButtons });
    };

    const onSelectBookImage = (media) => {
        setAttributes({
            bookImageId: media.id,
            bookImageUrl: media.url
        });
    };

    const onSelectStoreIcon = (index, media) => {
        const newButtons = [...storeButtons];
        newButtons[index] = { ...newButtons[index], iconImageUrl: media.url };
        setAttributes({ storeButtons: newButtons });
    };

    // Helper to generate stars
    const renderStars = () => {
        const stars = [];
        const fullStars = Math.floor(ratingStars);
        const hasHalf = (ratingStars - fullStars) >= 0.5;

        for (let i = 0; i < fullStars; i++) {
            stars.push(<span key={`star-${i}`}>★</span>);
        }
        if (hasHalf) {
            stars.push(<span key="star-half">★</span>);
        }
        return stars;
    };

    return (
        <div {...blockProps}>
            {/* SETTINGS TAB */}
            <InspectorControls>
                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    <TextControl
                        label={__('Badge Text', 'author-website-templates')}
                        value={badgeText}
                        onChange={(value) => setAttributes({ badgeText: value })}
                    />

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

                    <TextareaControl
                        label={__('Title', 'author-website-templates')}
                        value={title}
                        onChange={(value) => setAttributes({ title: value })}
                        help={__('Use <em>text</em> for accent color/italic style.', 'author-website-templates')}
                        rows={3}
                    />

                    <TextControl
                        label={__('Subtitle', 'author-website-templates')}
                        value={subtitle}
                        onChange={(value) => setAttributes({ subtitle: value })}
                    />

                    <TextareaControl
                        label={__('Description', 'author-website-templates')}
                        value={description}
                        onChange={(value) => setAttributes({ description: value })}
                        rows={4}
                    />

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

                    <h3>{__('Book Image', 'author-website-templates')}</h3>
                    <MediaUploadCheck>
                        <MediaUpload
                            onSelect={onSelectBookImage}
                            allowedTypes={['image']}
                            value={bookImageId}
                            render={({ open }) => (
                                <div>
                                    {bookImageUrl ? (
                                        <div>
                                            <img src={bookImageUrl} alt="" style={{ maxWidth: '200px', marginBottom: '10px' }} />
                                            <br />
                                            <Button onClick={open} variant="secondary">
                                                {__('Change Image', 'author-website-templates')}
                                            </Button>
                                            <Button
                                                onClick={() => setAttributes({ bookImageId: 0, bookImageUrl: '' })}
                                                variant="link"
                                                isDestructive
                                            >
                                                {__('Remove', 'author-website-templates')}
                                            </Button>
                                        </div>
                                    ) : (
                                        <Button onClick={open} variant="primary">
                                            {__('Select Book Image', 'author-website-templates')}
                                        </Button>
                                    )}
                                </div>
                            )}
                        />
                    </MediaUploadCheck>

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

                    <h3>{__('Rating', 'author-website-templates')}</h3>
                    <RangeControl
                        label={__('Stars', 'author-website-templates')}
                        value={ratingStars}
                        onChange={(value) => setAttributes({ ratingStars: value })}
                        min={0}
                        max={5}
                        step={0.5}
                    />

                    <TextControl
                        label={__('Rating Value', 'author-website-templates')}
                        value={ratingValue}
                        onChange={(value) => setAttributes({ ratingValue: value })}
                        placeholder="4.9/5"
                    />

                    <TextControl
                        label={__('Rating Text', 'author-website-templates')}
                        value={ratingText}
                        onChange={(value) => setAttributes({ ratingText: value })}
                        placeholder="Rating on Goodreads (10k+ Reviews)"
                    />
                </PanelBody>

                <PanelBody title={__('Store Buttons', 'author-website-templates')} initialOpen={false}>
                    {storeButtons.map((button, index) => (
                        <div key={button.id} style={{ marginBottom: '20px', padding: '15px', border: '1px solid #ddd', borderRadius: '4px' }}>
                            <h4>{__('Button', 'author-website-templates')} #{index + 1}</h4>

                            <SelectControl
                                label={__('Icon', 'author-website-templates')}
                                value={button.iconKey || ''}
                                options={[
                                    { label: __('Select an icon...', 'author-website-templates'), value: '' },
                                    ...PLATFORM_OPTIONS
                                ]}
                                onChange={(value) => updateStoreButton(index, 'iconKey', value)}
                            />

                            <p><strong>{__('OR Upload Custom Icon:', 'author-website-templates')}</strong></p>

                            {/* Pro Lock for Custom Icon Upload */}
                            <ProLock isLocked={!isPro}>
                                <MediaUploadCheck>
                                    <MediaUpload
                                        onSelect={(media) => onSelectStoreIcon(index, media)}
                                        allowedTypes={['image']}
                                        render={({ open }) => (
                                            <div>
                                                {button.iconImageUrl ? (
                                                    <div>
                                                        <img src={button.iconImageUrl} alt="" style={{ maxWidth: '50px', marginBottom: '5px' }} />
                                                        <br />
                                                        <Button onClick={open} variant="secondary" size="small">
                                                            {__('Change', 'author-website-templates')}
                                                        </Button>
                                                        <Button
                                                            onClick={() => updateStoreButton(index, 'iconImageUrl', '')}
                                                            variant="link"
                                                            isDestructive
                                                            size="small"
                                                        >
                                                            {__('Remove', 'author-website-templates')}
                                                        </Button>
                                                    </div>
                                                ) : (
                                                    <Button onClick={open} variant="secondary" size="small">
                                                        {__('Upload Icon', 'author-website-templates')}
                                                    </Button>
                                                )}
                                            </div>
                                        )}
                                    />
                                </MediaUploadCheck>
                            </ProLock>

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

                            <TextControl
                                label={__('Top Label', 'author-website-templates')}
                                value={button.topLabel}
                                onChange={(value) => updateStoreButton(index, 'topLabel', value)}
                                placeholder="Buy On"
                            />

                            <TextControl
                                label={__('Main Label', 'author-website-templates')}
                                value={button.mainLabel}
                                onChange={(value) => updateStoreButton(index, 'mainLabel', value)}
                                placeholder="Amazon"
                            />

                            <TextControl
                                label={__('URL', 'author-website-templates')}
                                value={button.url}
                                onChange={(value) => updateStoreButton(index, 'url', value)}
                                placeholder="#"
                            />

                            <Button
                                onClick={() => removeStoreButton(index)}
                                variant="secondary"
                                isDestructive
                            >
                                {__('Remove Button', 'author-website-templates')}
                            </Button>
                        </div>
                    ))}

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

                <PanelBody title={__('Floating Card', 'author-website-templates')} initialOpen={false}>
                    <ToggleControl
                        label={__('Show Floating Card', 'author-website-templates')}
                        checked={showFloatingCard}
                        onChange={(value) => setAttributes({ showFloatingCard: value })}
                    />

                    {showFloatingCard && (
                        <>
                            <TextControl
                                label={__('Top Label', 'author-website-templates')}
                                value={floatingCardTopLabel}
                                onChange={(value) => setAttributes({ floatingCardTopLabel: value })}
                                placeholder="Free"
                            />

                            <TextControl
                                label={__('Main Label', 'author-website-templates')}
                                value={floatingCardMainLabel}
                                onChange={(value) => setAttributes({ floatingCardMainLabel: value })}
                                placeholder="Read Sample"
                            />

                            <TextControl
                                label={__('URL', 'author-website-templates')}
                                value={floatingCardUrl}
                                onChange={(value) => setAttributes({ floatingCardUrl: value })}
                                placeholder="#"
                            />
                        </>
                    )}
                </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={300}
                        initialPosition={128}
                    />
                    <RangeControl
                        label={__('Bottom Padding (px)', 'author-website-templates')}
                        value={paddingBottom}
                        onChange={(value) => setAttributes({ paddingBottom: value })}
                        min={0}
                        max={300}
                        initialPosition={80}
                    />
                </PanelBody>

                <ProLock isLocked={!isPro}>
                    <PanelColorSettings
                        title={__('Design Settings', 'author-website-templates')}
                        initialOpen={false}
                        colorSettings={[
                            {
                                value: bgColor,
                                onChange: (value) => setAttributes({ bgColor: value }),
                                label: __('Background Color', 'author-website-templates'),
                            },
                            {
                                value: shapeColor,
                                onChange: (value) => setAttributes({ shapeColor: value }),
                                label: __('Shape Color', 'author-website-templates'),
                            },
                            {
                                value: accentColor,
                                onChange: (value) => setAttributes({ accentColor: value }),
                                label: __('Accent Color', 'author-website-templates'),
                            },
                            {
                                value: borderColor,
                                onChange: (value) => setAttributes({ borderColor: value }),
                                label: __('Border Color', 'author-website-templates'),
                            },
                        ]}
                    />
                </ProLock>
            </InspectorControls>

            {/* MAIN VISUAL EDITOR */}
            <section className="relative w-full h-full">
                {/* Background Shape */}
                <div
                    className="hero-shape absolute top-0 right-0 w-1/2 h-full bg-blue-50/50 rounded-bl-[100px] -z-10"
                    style={{ backgroundColor: shapeColor || undefined }}
                ></div>

                <div className="awt-container mx-auto px-6 lg:px-8">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-16 items-center">

                        {/* Left Content */}
                        <div className="order-2 md:order-1 space-y-8">

                            {/* Badge */}
                            <div className="inline-flex items-center gap-2 px-3 py-1 bg-yellow-100 text-yellow-800 rounded-full text-xs font-bold uppercase tracking-wider">
                                <svg className="w-4 h-4 fill-current" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
                                    <path d="M341.5 45.1C337.4 37.1 329.1 32 320.1 32C311.1 32 302.8 37.1 298.7 45.1L225.1 189.3L65.2 214.7C56.3 216.1 48.9 222.4 46.1 231C43.3 239.6 45.6 249 51.9 255.4L166.3 369.9L141.1 529.8C139.7 538.7 143.4 547.7 150.7 553C158 558.3 167.6 559.1 175.7 555L320.1 481.6L464.4 555C472.4 559.1 482.1 558.3 489.4 553C496.7 547.7 500.4 538.8 499 529.8L473.7 369.9L588.1 255.4C594.5 249 596.7 239.6 593.9 231C591.1 222.4 583.8 216.1 574.8 214.7L415 189.3L341.5 45.1z" />
                                </svg>
                                <RichText
                                    tagName="span"
                                    value={badgeText}
                                    onChange={(value) => setAttributes({ badgeText: value })}
                                    placeholder={__('Badge Text', 'author-website-templates')}
                                    allowedFormats={[]}
                                />
                            </div>

                            {/* Title & Description */}
                            <div>
                                <RichText
                                    tagName="h1"
                                    className="text-5xl lg:text-7xl font-serif font-bold text-primary leading-none mb-4"
                                    value={title}
                                    onChange={(value) => setAttributes({ title: value })}
                                    placeholder={__('Book Title', 'author-website-templates')}
                                    allowedFormats={['core/italic']} // Allow italic for accent styling
                                />

                                <RichText
                                    tagName="p"
                                    className="text-xl text-primary font-medium mb-4"
                                    value={subtitle}
                                    onChange={(value) => setAttributes({ subtitle: value })}
                                    placeholder={__('Subtitle...', 'author-website-templates')}
                                />

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

                            {/* Store Buttons */}
                            {storeButtons && storeButtons.length > 0 && (
                                <div className="pt-4 border-t border-gray-200" style={{ borderColor: borderColor || undefined }}>
                                    <p className="text-xs font-bold text-gray-400 uppercase tracking-widest mb-4">{__('Available On', 'author-website-templates')}</p>
                                    <div className="flex flex-wrap gap-4">
                                        {storeButtons.map((button, i) => (
                                            <div
                                                key={i}
                                                className="flex items-center gap-3 px-6 py-3 bg-white border border-gray-200 rounded-lg shadow-sm hover:border-accent hover:shadow-md transition group cursor-pointer"
                                                style={{ borderColor: borderColor || undefined }}
                                            >
                                                {button.iconImageUrl ? (
                                                    <img src={button.iconImageUrl} alt="" className="w-6 h-6 object-contain" />
                                                ) : (
                                                    <svg viewBox="0 0 576 512"
                                                        className="w-6 h-6 fill-current text-primary group-hover:text-accent transition"
                                                        style={accentColor ? { color: accentColor } : {}}
                                                    >
                                                        <path d={button.iconSvg}></path>
                                                    </svg>
                                                )}
                                                <div className="text-left">
                                                    <span className="block text-[10px] font-bold text-gray-400 uppercase leading-none">
                                                        {button.topLabel}
                                                    </span>
                                                    <span className="block text-sm font-bold text-primary">
                                                        {button.mainLabel}
                                                    </span>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {/* Rating */}
                            {ratingStars > 0 && (
                                <div className="flex items-center gap-4 text-sm font-medium text-gray-500">
                                    <div className="flex text-yellow-500 text-base">
                                        {renderStars()}
                                    </div>
                                    <span>{ratingValue} {ratingText}</span>
                                </div>
                            )}
                        </div>

                        {/* Right Content - Book Image */}
                        <div className="order-1 lg:order-2 flex justify-end md:justify-end lg:justify-end relative">
                            <div
                                className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-80 h-80 bg-accent/20 rounded-full blur-3xl -z-10"
                                style={accentColor ? { backgroundColor: accentColor, opacity: 0.2 } : {}}
                            ></div>

                            <div className="relative w-[320px] md:w-[400px] aspect-[2/3] transform rotate-[-3deg] hover:rotate-0 transition duration-700 ease-out cursor-pointer group">
                                <div className="absolute inset-0 bg-black/20 translate-y-4 translate-x-4 blur-lg rounded-lg -z-10 group-hover:translate-y-6 group-hover:translate-x-6 transition duration-700"></div>

                                <MediaUploadCheck>
                                    <MediaUpload
                                        onSelect={onSelectBookImage}
                                        allowedTypes={['image']}
                                        value={bookImageId}
                                        render={({ open }) => (
                                            <div onClick={open} className="relative w-full h-full">
                                                {bookImageUrl ? (
                                                    <img
                                                        src={bookImageUrl}
                                                        alt="Book Cover"
                                                        className="w-full h-full object-cover rounded-lg shadow-2xl border border-white/10"
                                                    />
                                                ) : (
                                                    <div className="w-full h-full flex items-center justify-center bg-gray-100 rounded-lg border-2 border-dashed border-gray-300 text-gray-400">
                                                        {__('Select Book Cover', 'author-website-templates')}
                                                    </div>
                                                )}

                                                {/* Hover Overlay to encourage clicking */}
                                                <div className="absolute inset-0 flex items-center justify-center bg-black/30 opacity-0 group-hover:opacity-100 transition rounded-lg">
                                                    <span className="text-white font-bold bg-black/50 px-4 py-2 rounded">
                                                        {__('Change Image', 'author-website-templates')}
                                                    </span>
                                                </div>
                                            </div>
                                        )}
                                    />
                                </MediaUploadCheck>

                                {/* Floating Card */}
                                {showFloatingCard && (
                                    <div className="absolute bottom-6 -left-6 bg-white px-6 py-3 rounded shadow-xl flex items-center gap-2 hover:scale-105 transition">
                                        <span
                                            className="w-8 h-8 rounded-full bg-accent text-white flex items-center justify-center"
                                            style={{ backgroundColor: accentColor || undefined }}
                                        >
                                            <svg viewBox="0 0 576 512" className="w-4 h-4 fill-current text-white">
                                                <path d="M187.2 100.9C174.8 94.1 159.8 94.4 147.6 101.6C135.4 108.8 128 121.9 128 136L128 504C128 518.1 135.5 531.2 147.6 538.4C159.7 545.6 174.8 545.9 187.2 539.1L523.2 355.1C536 348.1 544 334.6 544 320C544 305.4 536 291.9 523.2 284.9L187.2 100.9z" />
                                            </svg>
                                        </span>
                                        <div>
                                            <RichText
                                                tagName="span"
                                                className="block text-xs font-bold text-gray-400 uppercase"
                                                value={floatingCardTopLabel}
                                                onChange={(val) => setAttributes({ floatingCardTopLabel: val })}
                                                placeholder="Free"
                                            />
                                            <RichText
                                                tagName="h4"
                                                className="text-sm m-0 font-bold text-primary"
                                                value={floatingCardMainLabel}
                                                onChange={(val) => setAttributes({ floatingCardMainLabel: val })}
                                                placeholder="Read Sample"
                                            />
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>

                    </div>
                </div>

                {/* Inline Styles for dynamic colors to match render.php's scoped styles behavior */}
                <style>
                    {`
                        #${blockId} em {
                            color: ${accentColor || 'inherit'} !important;
                            font-style: italic;
                        }
                    `}
                </style>
            </section>
        </div>
    );
}
