import React, { useState, useRef, useImperativeHandle, forwardRef } from 'react';

const PreviewPanel = forwardRef(({ previewData, showcaseData, isLoading, onRefresh }, ref) => {
    const [previewDevice, setPreviewDevice] = useState('desktop');
    const previewHtmlRef = useRef(null);

    // Expose method to update CSS variables directly
    useImperativeHandle(ref, () => ({
        updateCSSVariable: (property, value) => {
            if (previewHtmlRef.current) {
                // Update the outer preview-html element
                previewHtmlRef.current.style.setProperty(property, value);
                
                // Also update the inner wcps-container element if it exists
                const innerContainer = previewHtmlRef.current.querySelector('.wcps-container');
                if (innerContainer) {
                    innerContainer.style.setProperty(property, value);
                }
            }
        },
        updateMultipleCSSVariables: (variables) => {
            if (previewHtmlRef.current) {
                Object.entries(variables).forEach(([property, value]) => {
                    if (value !== null && value !== undefined) {
                        // Update the outer preview-html element
                        previewHtmlRef.current.style.setProperty(property, value);
                        
                        // Also update the inner wcps-container element if it exists
                        const innerContainer = previewHtmlRef.current.querySelector('.wcps-container');
                        if (innerContainer) {
                            innerContainer.style.setProperty(property, value);
                        }
                    }
                });
            }
        }
    }), []);

    // Generate CSS variables from showcase data
    const generateCSSVariables = (data) => {
        if (!data) return {};

        const cssVars = {};

        // Helper function to check if value is valid
        const isValidValue = (value) => {
            return value !== undefined && value !== null && value !== '';
        };

        // CSS Variable mappings with their corresponding data keys
        const cssVariableMappings = {
            // Container variables
            '--wcps-container-background': data.container_background,
            '--wcps-container-padding': data.container_padding,
            '--wcps-container-margin': data.container_margin,

            // Grid variables
            '--wcps-columns': data.columns,
            '--wcps-grid-gap': data.grid_gap ? `${data.grid_gap}px` : null,
            '--wcps-grid-width': data.grid_width,

            // Product variables
            '--wcps-product-background': data.product_background,
            '--wcps-product-content-padding': data.product_content_padding ? `${data.product_content_padding}px` : null,

            // Title variables
            '--wcps-product-title': data.product_title,
            '--wcps-product-title-hover-color': data.product_title_hover_color,
            '--wcps-title-size': data.title_size ? `${data.title_size}px` : null,
            '--wcps-title-weight': data.title_weight,

            // Description variables
            '--wcps-description-color': data.description_color,
            '--wcps-desc-size': data.desc_size ? `${data.desc_size}px` : null,

            // Price variables
            '--wcps-price-delete-font-color': data.price_delete_color,
            '--wcps-price-font-color': data.price_color,
            '--wcps-price-font-size': data.price_size ? `${data.price_size}px` : null,
            '--wcps-price-font-weight': data.price_weight,

            // Star variables
            '--wcps-star-size': data.star_size ? `${data.star_size}px` : null,
            '--wcps-star-color': data.star_color,

            // Text alignment
            '--wcps-text-align': data.text_align,

            // Border variables
            '--wcps-border-radius': data.border_radius ? `${data.border_radius}px` : null,
            '--wcps-border-style': data.border_style,
            '--wcps-border-width': data.border_width ? `${data.border_width}px` : null,
            '--wcps-border-color': data.border_color,

            // Image variables
            '--wcps-product-image-width': data.product_image_width,
            '--wcps-product-image-height': data.product_image_height,
            '--wcps-image-aspect-ratio': data.image_aspect_ratio,
            '--wcps-image-border-radius': data.image_border_radius ? `${data.image_border_radius}px` : null,

            // Badge variables
            '--wcps-product-badge-background': data.product_badge_background,
            '--wcps-product-badge-font-color': data.product_badge_font_color,
            '--wcps-product-badge-font-size': data.product_badge_font_size ? `${data.product_badge_font_size}px` : null,
            '--wcps-product-badge-font-weight': data.product_badge_font_weight,
            '--wcps-product-badge-text-align': data.product_badge_text_align,
            '--wcps-product-badge-text-transform': data.product_badge_text_transform,
            '--wcps-product-badge-border-radius': data.product_badge_border_radius ? `${data.product_badge_border_radius}px` : null,
            '--wcps-product-badge-padding': data.product_badge_padding,
            '--wcps-product-badge-margin': data.product_badge_margin,

            // Button variables
            '--wcps-button-border-radius': data.button_border_radius ? `${data.button_border_radius}px` : null,
            '--wcps-button-bg-color': data.button_bg_color,
            '--wcps-button-text-color': data.button_text_color,
            '--wcps-button-hover-bg': data.button_hover_bg,
            '--wcps-button-hover-text-color': data.button_hover_text_color,
            '--wcps-button-font-size': data.button_font_size ? `${data.button_font_size}px` : null,
            '--wcps-button-padding': data.button_padding,
            '--wcps-button-margin': data.button_margin,
            '--wcps-button-border': data.button_border,
            '--wcps-button-hover-border': data.button_hover_border,
            '--wcps-button-animation': data.button_animation,

            // Product layout variables
            '--wcps-product-width': data.product_width,
            '--wcps-product-flex': data.product_flex,
            '--wcps-product-content-background': data.product_content_background,
            '--wcps-product-content-margin': data.product_content_margin,
            '--wcps-product-content-direction': data.product_content_direction,

            // Effects variables
            '--wcps-box-shadow': data.box_shadow,
            '--wcps-image-hover-effect': data.image_hover_effect,
            '--wcps-hover-effect': data.hover_effect,
            '--wcps-hover-transition': data.hover_transition ? `${data.hover_transition}s` : null,
            // Action icon variables
            '--wcps-compare-icon': data.compare_icon,
            '--wcps-wishlist-icon': data.wishlist_icon,
            '--wcps-quickview-icon': data.quickview_icon,
            '--wcps-addtocart-icon': data.addtocart_icon
        };

        // Only add variables that have valid values
        Object.entries(cssVariableMappings).forEach(([cssVar, value]) => {
            if (isValidValue(value)) {
                cssVars[cssVar] = value;
            }
        });

        return cssVars;
    };

    const deviceSizes = {
        desktop: { width: '100%', height: 'auto' },
        tablet: { width: '768px', height: '1024px' },
        mobile: { width: '375px', height: '667px' }
    };

    const generateShortcode = () => {
        if (showcaseData.id) {
            return `[product_display id="${showcaseData.id}"]`;
        } else {
            return `Save showcase to get shortcode`;
        }
    };

    const copyShortcode = (event) => {
        if (!showcaseData.id) {
            alert('Please save the showcase first to get the shortcode.');
            return;
        }

        const shortcode = generateShortcode();
        navigator.clipboard.writeText(shortcode);

        // Show a simple notification
        const button = event.target.closest('button');
        const originalText = button.innerHTML;
        button.innerHTML = '<span class="dashicons dashicons-yes"></span>';
        button.style.color = '#46b450';

        setTimeout(() => {
            button.innerHTML = originalText;
            button.style.color = '';
        }, 2000);
    };

    return (
        <div className="proddisp-preview-panel">
            <div className="preview-header">
                <div className="preview-title">
                    <h3><i className="fas fa-search"></i> Live Preview</h3>
                    <span className="preview-subtitle">See your changes in real-time</span>
                </div>
                <div className="preview-controls">
                    <div className="device-selector">
                        {/* <button
                            className={`device-btn ${previewDevice === 'desktop' ? 'active' : ''}`}
                            onClick={() => setPreviewDevice('desktop')}
                            title="Desktop View"
                        >
                            <i className="fas fa-desktop"></i>
                        </button>
                        <button
                            className={`device-btn ${previewDevice === 'tablet' ? 'active' : ''}`}
                            onClick={() => setPreviewDevice('tablet')}
                            title="Tablet View"
                        >
                            <i className="fas fa-tablet-alt"></i>
                        </button>
                        <button
                            className={`device-btn ${previewDevice === 'mobile' ? 'active' : ''}`}
                            onClick={() => setPreviewDevice('mobile')}
                            title="Mobile View"
                        >
                            <i className="fas fa-mobile-alt"></i>
                        </button> */}
                    </div>
                    <button
                        className="refresh-preview"
                        onClick={onRefresh}
                        disabled={isLoading}
                        title="Refresh Preview"
                    >
                        <i className={`fas fa-sync-alt ${isLoading ? 'fa-spin' : ''}`}></i>
                    </button>
                </div>
            </div>

            <div className="preview-content">
                <div
                    className={`preview-frame preview-${previewDevice}`}
                    style={deviceSizes[previewDevice]}
                >
                    {isLoading ? (
                        <div className="preview-loading">
                            <div className="loading-content">
                                <span className="dashicons dashicons-update-alt spinning"></span>
                                <p>Generating preview...</p>
                            </div>
                        </div>
                    ) : previewData ? (
                        <div
                            ref={previewHtmlRef}
                            className="preview-html"
                            style={generateCSSVariables(showcaseData)}
                            dangerouslySetInnerHTML={{ __html: previewData }}
                        />
                    ) : (
                        <div className="preview-placeholder">
                            <div className="placeholder-content">
                                <span className="dashicons dashicons-products"></span>
                                <p>Configure your showcase settings to see a preview</p>
                            </div>
                        </div>
                    )}
                </div>
            </div>

            <div className="preview-footer">
                <div className="shortcode-section">
                    <div className="shortcode-header">
                        <i className="shortcode-icon fas fa-code"></i>
                        <label>Shortcode</label>
                    </div>
                    <div className="shortcode-container">
                        <input
                            type="text"
                            value={generateShortcode()}
                            readOnly
                            className="shortcode-input"
                        />
                        <button
                            className="copy-shortcode-button"
                            onClick={copyShortcode}
                            title="Copy Shortcode"
                        >
                            <i className="fas fa-copy"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
});

export default PreviewPanel;