import React, { useState, useEffect } from 'react';
import ProUpgradeModal from './ProUpgradeModal';

const LayoutSelector = ({ onLayoutSelected, onBack }) => {
    const [selectedLayout, setSelectedLayout] = useState(null);
    const [step, setStep] = useState('layout'); // 'layout', 'mode', 'style'
    const [showcaseName, setShowcaseName] = useState(`New Showcase - ${new Date().toLocaleString()}`);
    const [previews, setPreviews] = useState({});
    const [loadingPreviews, setLoadingPreviews] = useState({});
    const [proModal, setProModal] = useState({ isOpen: false, feature: '' });

    // Check if pro version is active (same as ProductSelector.jsx)
    const isProActive = proddispAdmin.isProActive;

    // URL management functions
    const updateURL = (step, layout = null) => {
        const url = new URL(window.location);
        url.searchParams.set('page', 'product-display');
        url.searchParams.set('view', 'layout-selector');
        url.searchParams.set('step', step);

        if (layout) {
            url.searchParams.set('layout', layout);
        } else {
            url.searchParams.delete('layout');
        }

        window.history.pushState({ step, layout }, '', url.toString());
    };

    const getURLParams = () => {
        const urlParams = new URLSearchParams(window.location.search);
        return {
            step: urlParams.get('step') || 'layout',
            layout: urlParams.get('layout')
        };
    };

    // Initialize from URL on component mount
    useEffect(() => {
        const params = getURLParams();
        if (params.step && params.step !== step) {
            setStep(params.step);
        }
        if (params.layout && params.layout !== selectedLayout) {
            setSelectedLayout(params.layout);
        }
    }, []);

    // Handle browser back/forward buttons
    useEffect(() => {
        const handlePopState = (event) => {
            if (event.state && event.state.step) {
                setStep(event.state.step);
                setSelectedLayout(event.state.layout || null);
            } else {
                const params = getURLParams();
                setStep(params.step);
                setSelectedLayout(params.layout);
            }
        };

        window.addEventListener('popstate', handlePopState);
        return () => window.removeEventListener('popstate', handlePopState);
    }, []);

    const layouts = {
        'grid': {
            title: 'Basic Grid',
            description: 'Simple grid layout for displaying products',
            icon: 'dashicons-grid-view',
            isPro: false,
            modes: {
                'basic-grid': 'Style 1',
                'basic-grid-2': 'Style 2 (Pro)',
                'basic-grid-3': 'Style 3 (Pro)'
            }
        },
        'card_grid': {
            title: 'Card Grid',
            description: 'Card-based grid layout with enhanced styling',
            icon: 'dashicons-screenoptions',
            isPro: false,
            modes: {
                'card-grid': 'Style 1',
                'card-grid-2': 'Style 2 (Pro)',
                'card-grid-3': 'Style 3 (Pro)'
            }
        },
        'slider': {
            title: 'Slider',
            description: 'Carousel slider for showcasing products',
            icon: 'dashicons-slides',
            isPro: false,
            modes: {
                'slider': 'Style 1',
                'slider-2': 'Style 2 (Pro)',
                'slider-3': 'Style 3 (Pro)'
            }
        },
        'masonry_grid': {
            title: 'Masonry Grid',
            description: 'Pinterest-style masonry layout',
            icon: 'dashicons-layout',
            isPro: true,
            modes: {
                'masonry-grid': 'Style 1 (Pro)',
                'masonry-grid-2': 'Style 2 (Pro)',
                'masonry-grid-3': 'Style 3 (Pro)'
            }
        },
        'gallery': {
            title: 'Gallery',
            description: 'Gallery layout for product showcase',
            icon: 'dashicons-format-gallery',
            isPro: false,
            modes: {
                'gallery': 'Style 1',
                'gallery-2': 'Style 2 (Pro)',
                'gallery-3': 'Style 3 (Pro)'
            }
        },
        'flip': {
            title: 'Flip Layout',
            description: 'Interactive flip cards for products',
            icon: 'dashicons-image-flip-horizontal',
            isPro: true,
            modes: {
                'flip-layout': 'Style 1 (Pro)',
                'flip-layout-2': 'Style 2 (Pro)',
                'flip-layout-3': 'Style 3 (Pro)',
                'flip-layout-4': 'Style 4 (Pro)',
                'flip-layout-5': 'Style 5 (Pro)'
            }
        },
        'table': {
            title: 'Table Layout',
            description: 'Table format for product comparison',
            icon: 'dashicons-editor-table',
            isPro: false,
            modes: {
                'table': 'Style 1',
                'table-2': 'Style 2 (Pro)',
                'table-3': 'Style 3 (Pro)'
            }
        },
        'showcase': {
            title: 'Showcase',
            description: 'Premium showcase layout',
            icon: 'dashicons-star-filled',
            isPro: true,
            modes: {
                'showcase': 'Style 1 (Pro)',
                'showcase-2': 'Style 2 (Pro)',
                'showcase-3': 'Style 3 (Pro)'
            }
        },
        'category_tabs': {
            title: 'Category Tabs',
            description: 'Tabbed layout organized by categories',
            icon: 'dashicons-category',
            isPro: false,
            modes: {
                'category_tabs': 'Style 1',
                'category_tabs_2': 'Style 2 (Pro)',
                'category_tabs_3': 'Style 3 (Pro)'
            }
        },
        'list': {
            title: 'List Layout',
            description: 'List format for detailed product display',
            icon: 'dashicons-list-view',
            isPro: false,
            modes: {
                'list-layout': 'Style 1',
                'list-layout-2': 'Style 2 (Pro)',
                'list-layout-3': 'Style 3 (Pro)'
            }
        },
        'cta': {
            title: 'CTA Layout',
            description: 'Call-to-action focused layout',
            icon: 'dashicons-megaphone',
            isPro: true,
            modes: {
                'cta-layout': 'Style 1 (Pro)',
                'cta-layout-2': 'Style 2 (Pro)',
                'cta-layout-3': 'Style 3 (Pro)'
            }
        },
        'caption': {
            title: 'Caption Layouts',
            description: 'Animated caption overlays with hover effects',
            icon: 'dashicons-format-image',
            isPro: false,
            modes: {
                'blinds-vertical': 'Blinds Vertical',
                'blocks-zoom-top-left': 'Blocks Zoom Top Left',

                'book-open-horizontal': 'Book Open Horizontal  (Pro)',
                'border-reveal-top-left': 'Border Reveal Top Left  (Pro)',
                'bounce-out-right': 'Bounce Out Right  (Pro)',
                'circle-top-left': 'Circle Top Left  (Pro)',
                'cube-left': 'Cube Left  (Pro)',
                'swiper-slide': 'Swiper Slide  (Pro)',
                'liquid-morph': 'Liquid Morph  (Pro)',
                'neon-glow': 'Neon Glow  (Pro)',
                'origami-fold': 'Origami Fold  (Pro)',
                'particle-burst': 'Particle Burst  (Pro)',
                'hologram': 'Hologram Effect  (Pro)',
                'glass-shatter': 'Glass Shatter  (Pro)',
                'magnetic-pull': 'Magnetic Pull  (Pro)',
                'quantum-tunnel': 'Quantum Tunnel  (Pro)',
                'fire-ignition': 'Fire Ignition  (Pro)',
                'matrix-rain': 'Matrix Rain  (Pro)'
            }
        }
    };

    const handleLayoutSelect = (layoutKey) => {
        setSelectedLayout(layoutKey);
        setStep('mode');
        updateURL('mode', layoutKey);
    };

    const handleModeSelect = (mode) => {
        onLayoutSelected(selectedLayout, mode, showcaseName);
    };

    // Generate preview for a specific layout and mode
    const generatePreview = async (layout, mode) => {
        const previewKey = `${layout}-${mode}`;

        if (previews[previewKey] || loadingPreviews[previewKey]) {
            return; // Already loaded or loading
        }

        setLoadingPreviews(prev => ({ ...prev, [previewKey]: true }));

        try {
            // Create complete sample showcase data for preview with all styling properties
            const sampleData = {
                // Basic layout settings
                layout: layout,
                proddisp_layout_mode: mode,
                product_source: 'specific',
                products: [], // Empty - will use sample products
                limit: 4,
                columns: 3,
                orderby: 'date',
                order: 'DESC',

                // Display elements
                show_title: 'yes',
                show_price: 'yes',
                show_rating: 'yes',
                show_description: 'no',
                excerpt_length: 20,

                // Action buttons
                show_addtocart: 'yes',
                show_compare: 'yes',
                show_quickview: 'yes',
                show_wishlist: 'yes',

                // Action button display modes
                addtocart_display_mode: 'icon_text',
                compare_display_mode: 'icon_text',
                quickview_display_mode: 'icon_text',
                wishlist_display_mode: 'icon_text',

                // Action button icons
                addtocart_icon: 'fas fa-shopping-cart',
                compare_icon: 'fas fa-chart-bar',
                quickview_icon: 'fas fa-eye',
                wishlist_icon: 'fas fa-heart',

                // Action position
                action_position: 'hover',

                // Container styles
                container_background: '#ffffff',
                container_padding: '25',
                container_margin: '0',

                // Grid styles
                grid_gap: '20px',
                grid_width: '100%',

                // Product styles
                product_background: '#ffffff',
                product_content_padding: '15',
                product_title: '#0170B9',
                product_title_hover_color: '#015293',
                title_size: '16px',
                title_weight: '600',
                description_color: '#23282d',
                desc_size: '14px',
                price_delete_color: '#333333',
                price_color: '#0170B9',
                price_size: '18px',
                price_weight: '700',
                star_size: '14px',
                star_color: '#ffc107',
                text_align: 'left',

                // Border and styling
                border_radius: '4px',
                border_style: 'solid',
                border_width: '1px',
                border_color: '#eeeeee',

                // Image styles
                product_image_width: '100%',
                product_image_height: 'auto',
                image_aspect_ratio: '1/1',

                // Badge styles
                product_badge_background: 'rgb(54, 182, 217)',
                product_badge_font_color: '#ffffff',
                product_badge_font_size: '12px',
                product_badge_font_weight: '400',
                product_badge_text_align: 'center',
                product_badge_text_transform: 'none',
                product_badge_border_radius: '20px',
                product_badge_padding: '5px',
                product_badge_margin: '0px',

                // Button styles
                button_border_radius: '4px',
                button_bg_color: '#0170B9',
                button_text_color: '#ffffff',
                button_hover_bg: '#015293',
                button_hover_text_color: '#ffffff',
                button_font_size: '14px',
                button_padding: '8px 12px',
                button_margin: '0px'
            };

            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_get_shortcode_preview',
                    nonce: proddispAdmin.nonce,
                    data: JSON.stringify(sampleData)
                })
            });

            const result = await response.json();
            if (result.success) {
                setPreviews(prev => ({ ...prev, [previewKey]: result.data.html }));
            } else {
                console.error('Preview generation failed:', result.data?.message);
                setPreviews(prev => ({ ...prev, [previewKey]: '<div class="preview-error">Preview not available</div>' }));
            }
        } catch (error) {
            console.error('Error generating preview:', error);
            setPreviews(prev => ({ ...prev, [previewKey]: '<div class="preview-error">Preview not available</div>' }));
        } finally {
            setLoadingPreviews(prev => ({ ...prev, [previewKey]: false }));
        }
    };

    // Load previews when mode selection step is reached
    useEffect(() => {
        if (step === 'mode' && selectedLayout) {
            const layout = layouts[selectedLayout];
            Object.keys(layout.modes).forEach(mode => {
                // Generate previews for all modes
                generatePreview(selectedLayout, mode);
            });
        }
    }, [step, selectedLayout]);

    const renderLayoutSelection = () => (
        <div className="proddisp-layout-selection">
            <div className="proddisp-header">
                <div className="header-actions">
                    <button
                        className="button"
                        onClick={onBack}
                    >
                        ← Back to Showcases
                    </button>
                </div>
                <h1>Choose a Layout Type</h1>
                <p>Select the type of layout you want to use for your product showcase.</p>
            </div>
            <div className="proddisp-layout-grid">
                {Object.entries(layouts).map(([key, layout]) => {
                    // const isLayoutPro = layout.isPro;
                    // const canUseLayout = !isLayoutPro || isProActive;

                    return (
                        <div key={key} className={`proddisp-layout-card`}>
                            <div className="proddisp-layout-icon">
                                <span className={`dashicons ${layout.icon}`}></span>
                            </div>
                            <h3>{layout.title}</h3>
                            <p>{layout.description}</p>
                            <button
                                className="button button-primary"
                                onClick={() => handleLayoutSelect(key)}
                            >
                                Choose Layout
                            </button>
                        </div>
                    );
                })}
            </div>
        </div>
    );

    const renderModeSelection = () => {
        const layout = layouts[selectedLayout];

        return (
            <div className="proddisp-mode-selection">
                <div className="proddisp-header">
                    <div className="header-actions">
                        <button
                            className="button"
                            onClick={() => {
                                setStep('layout');
                                updateURL('layout');
                            }}
                        >
                            ← Back to Layouts
                        </button>
                        <button
                            className="button"
                            onClick={onBack}
                        >
                            Cancel
                        </button>
                    </div>
                    <h1>Choose a Style for {layout.title}</h1>
                    <p>Select the style variation you want to use.</p>
                </div>
                <div className="proddisp-mode-grid">
                    {Object.entries(layout.modes).map(([modeKey, modeTitle]) => {
                        const isProFeature = modeTitle.includes('(Pro)');

                        return (
                            <div key={modeKey} className={`proddisp-mode-card ${isProFeature && !isProActive ? 'pro-feature' : ''}`}>
                                <div className="proddisp-style-preview">
                                    {(() => {
                                        const previewKey = `${selectedLayout}-${modeKey}`;
                                        if (loadingPreviews[previewKey]) {
                                            return (
                                                <div className="preview-loading">
                                                    <div className="spinner"></div>
                                                    <span>Loading preview...</span>
                                                </div>
                                            );
                                        } else if (previews[previewKey]) {
                                            return (
                                                <div
                                                    className="preview-content"
                                                    dangerouslySetInnerHTML={{ __html: previews[previewKey] }}
                                                />
                                            );
                                        } else if (isProFeature && !isProActive) {
                                            return (
                                                <div className="preview-placeholder pro-preview">
                                                    <span className="dashicons dashicons-lock"></span>
                                                    <span>Pro Preview</span>
                                                </div>
                                            );
                                        } else {
                                            return (
                                                <div className="preview-placeholder">
                                                    <span>Preview</span>
                                                </div>
                                            );
                                        }
                                    })()}
                                </div>
                                <div className="proddisp-mode-content">
                                    <h3>{modeTitle}</h3>
                                    <div className="proddisp-name-input">
                                        <label>Showcase Name</label>
                                        <input
                                            type="text"
                                            value={showcaseName}
                                            onChange={(e) => setShowcaseName(e.target.value)}
                                            className="regular-text"
                                            required
                                            disabled={isProFeature && !isProActive}
                                        />
                                        <p className="description">Enter a name for your showcase (for admin reference only).</p>
                                    </div>
                                    {isProFeature && !isProActive ? (
                                        <button
                                            className="button button-primary"
                                            onClick={() => setProModal({
                                                isOpen: true,
                                                feature: `${layout.title} - ${modeTitle}`
                                            })}
                                            title="This feature requires the Pro version"
                                        >
                                            Upgrade to Pro
                                        </button>
                                    ) : (
                                        <button
                                            className="button button-primary"
                                            onClick={() => handleModeSelect(modeKey)}
                                            disabled={!showcaseName.trim()}
                                        >
                                            Select Style
                                        </button>
                                    )}
                                </div>
                            </div>
                        );
                    })}
                </div>
            </div>
        );
    };

    return (
        <div className="proddisp-layout-selector">
            {step === 'layout' && renderLayoutSelection()}
            {step === 'mode' && renderModeSelection()}

            <ProUpgradeModal
                isOpen={proModal.isOpen}
                onClose={() => setProModal({ isOpen: false, feature: '' })}
                feature={proModal.feature}
            />
        </div>
    );
};

export default LayoutSelector;