import React, { useState, useEffect } from 'react';
import ShowcaseList from './components/ShowcaseList';
import ShowcaseEditor from './components/ShowcaseEditor';
import LayoutSelector from './components/LayoutSelector';
import ShortcodeGenerator from './components/ShortcodeGenerator';
import GetStarted from './components/GetStarted';
import ToastContainer from './components/ToastContainer';


const App = ({ editId, initialView }) => {
    const [currentView, setCurrentView] = useState('list');
    const [showcases, setShowcases] = useState([]);
    const [editingShowcase, setEditingShowcase] = useState(null);
    const [loading, setLoading] = useState(true);
    
    // Layout initialization is now handled automatically by Helpers.js

    // URL management functions
    const updateURL = (view, params = {}) => {
        const url = new URL(window.location);
        url.searchParams.set('page', 'product-display');

        if (view !== 'list') {
            url.searchParams.set('view', view);
        } else {
            url.searchParams.delete('view');
        }

        // Add specific parameters
        Object.keys(params).forEach(key => {
            if (params[key]) {
                url.searchParams.set(key, params[key]);
            } else {
                url.searchParams.delete(key);
            }
        });

        window.history.pushState({ view, params }, '', url.toString());
    };

    const getURLParams = () => {
        const urlParams = new URLSearchParams(window.location.search);
        return {
            view: urlParams.get('view') || 'list',
            edit: urlParams.get('edit'),
            create: urlParams.get('create'),
            step: urlParams.get('step'),
            layout: urlParams.get('layout')
        };
    };

    // Initialize view from URL
    useEffect(() => {
        const params = getURLParams();

        if (editId || params.edit) {
            setCurrentView('editor');
        } else if (initialView === 'create' || params.create || params.view === 'layout-selector') {
            setCurrentView('layout-selector');
        } else if (params.view === 'shortcode-generator') {
            setCurrentView('shortcode-generator');
        } else if (params.view === 'get-started') {
            setCurrentView('get-started');
        } else {
            setCurrentView('list');
        }
    }, [editId, initialView]);

    // Handle browser back/forward buttons
    useEffect(() => {
        const handlePopState = (event) => {
            const params = getURLParams();

            if (event.state) {
                setCurrentView(event.state.view);
            } else {
                setCurrentView(params.view);
            }

            // Clear editing showcase when navigating back to list
            if (params.view === 'list') {
                setEditingShowcase(null);
            }
        };

        window.addEventListener('popstate', handlePopState);
        return () => window.removeEventListener('popstate', handlePopState);
    }, []);

    useEffect(() => {
        loadShowcases();
    }, []);

    // Separate effect for loading showcase for edit
    useEffect(() => {
        if (editId && showcases.length > 0) {
            loadShowcaseForEdit(editId);
        }
    }, [editId, showcases]);

    const loadShowcases = async () => {
        try {
            setLoading(true);
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_get_showcases',
                    nonce: proddispAdmin.nonce
                })
            });

            const data = await response.json();
            console.log('Showcases response:', data); // Debug log

            if (data.success) {
                setShowcases(data.data.showcases || []);
            } else {
                console.error('Error loading showcases:', data.data?.message || 'Unknown error');
                setShowcases([]);
            }
        } catch (error) {
            console.error('Error loading showcases:', error);
            setShowcases([]);
        } finally {
            setLoading(false);
        }
    };

    const loadShowcaseForEdit = async (showcaseId) => {
        try {
            console.log('Loading showcase for edit:', showcaseId);
            console.log('Available showcases:', showcases.map(s => ({ id: s.id, name: s.name })));

            // First try to find showcase in already loaded showcases
            // Convert both to strings for comparison since URL params are strings
            let showcase = showcases.find(s => String(s.id) === String(showcaseId));

            if (showcase) {
                console.log('Found showcase in loaded data:', showcase.name);
                setEditingShowcase(showcase);
                return;
            }

            console.log('Showcase not found in loaded data, fetching all showcases...');

            // If not found, load all showcases first and then find the specific one
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_get_showcases',
                    nonce: proddispAdmin.nonce
                })
            });

            const data = await response.json();

            if (data.success && data.data.showcases) {
                const allShowcases = data.data.showcases;
                setShowcases(allShowcases);

                // Now find the specific showcase
                // Convert both to strings for comparison since URL params are strings
                showcase = allShowcases.find(s => String(s.id) === String(showcaseId));
                if (showcase) {
                    setEditingShowcase(showcase);
                } else {
                    console.error('Showcase not found with ID:', showcaseId);
                    console.log('Available showcase IDs:', allShowcases.map(s => s.id));
                    // Redirect to list view if showcase not found
                    setCurrentView('list');
                    updateURL('list');
                }
            } else {
                console.error('Error loading showcases for edit:', data.data?.message || 'Unknown error');
            }
        } catch (error) {
            console.error('Error loading showcase for edit:', error);
        }
    };

    const handleCreateNew = () => {
        setEditingShowcase(null);
        setCurrentView('layout-selector');
        updateURL('layout-selector', { create: 'true', step: 'layout' });
    };

    const handleEdit = (showcase) => {
        setEditingShowcase(showcase);
        setCurrentView('editor');
        updateURL('editor', { edit: showcase.id });
    };

    const handleDuplicate = async (showcase) => {
        try {
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_duplicate_showcase',
                    nonce: proddispAdmin.nonce,
                    showcase_id: showcase.id
                })
            });

            const data = await response.json();
            if (data.success && data.data.showcase) {
                // Reload showcases to include the new duplicate
                await loadShowcases();

                // Show success message
                if (window.proddispToast) {
                    window.proddispToast.success(`Showcase duplicated as "${data.data.showcase.name}"`);
                }
            } else {
                console.error('Error duplicating showcase:', data.data?.message || 'Unknown error');
                if (window.proddispToast) {
                    window.proddispToast.error('Failed to duplicate showcase: ' + (data.data?.message || 'Unknown error'));
                }
            }
        } catch (error) {
            console.error('Error duplicating showcase:', error);
            if (window.proddispToast) {
                window.proddispToast.error('Error duplicating showcase. Please try again.');
            }
        }
    };

    const handleLayoutSelected = async (layout, mode, name) => {
        try {
            // Load preset values from backend
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_get_preset_values',
                    nonce: proddispAdmin.nonce,
                    layout_mode: mode
                })
            });

            const data = await response.json();
            let presetValues = {};

            if (data.success && data.data.preset_values) {
                presetValues = data.data.preset_values;
            } else {
                console.warn('Failed to load preset values, using defaults');
            }

            // Create new showcase with preset values
            const newShowcase = {
                id: '', // Will be generated on save
                layout,
                proddisp_layout_mode: mode,
                name: name || `New Showcase - ${new Date().toLocaleString()}`,

                // Product source settings
                product_source: 'specific',
                products: [],
                category: [],
                tag: [],
                brand: [],
                attribute: '',
                attribute_terms: [],

                // Use preset values with fallbacks
                limit: presetValues.limit || 4,
                columns: presetValues.columns || 4,
                orderby: presetValues.orderby || 'date',
                order: presetValues.order || 'DESC',
                image_size: presetValues.image_size || 'woocommerce_thumbnail',

                // Display settings
                show_title: presetValues.show_title || 'yes',
                show_price: presetValues.show_price || 'yes',
                show_rating: presetValues.show_rating || 'yes',
                show_description: presetValues.show_description || 'no',
                excerpt_length: presetValues.excerpt_length || 20,

                // Action buttons
                show_addtocart: presetValues.show_addtocart || 'yes',
                show_compare: presetValues.show_compare || 'yes',
                show_quickview: presetValues.show_quickview || 'yes',
                show_wishlist: presetValues.show_wishlist || 'yes',
                action_position: presetValues.action_position || 'hover',

                // Action button display modes
                addtocart_display_mode: presetValues.addtocart_display_mode || 'icon_text',
                compare_display_mode: presetValues.compare_display_mode || 'icon_only',
                quickview_display_mode: presetValues.quickview_display_mode || 'icon_only',
                wishlist_display_mode: presetValues.wishlist_display_mode || 'icon_only',

                // Action button icons
                addtocart_icon: presetValues.addtocart_icon || 'fas fa-shopping-cart',
                compare_icon: presetValues.compare_icon || 'fas fa-chart-bar',
                quickview_icon: presetValues.quickview_icon || 'fas fa-eye',
                wishlist_icon: presetValues.wishlist_icon || 'fas fa-heart',

                // Slider settings
                autoplay: presetValues.autoplay || 'yes',
                arrows: presetValues.arrows || 'yes',
                dots: presetValues.dots || 'yes',
                slide_speed: presetValues.slide_speed || 3000,

                // AJAX settings
                enable_ajax: presetValues.enable_ajax || 'no',
                enable_filters: presetValues.enable_filters || 'no',
                enable_pagination: presetValues.enable_pagination || 'no',
                pagination_per_page: presetValues.pagination_per_page || 4,

                // Styling properties from preset
                container_background: presetValues.container_background || '#ffffff',
                container_padding: presetValues.container_padding || '25px',
                container_margin: presetValues.container_margin || '0px',
                grid_gap: presetValues.grid_gap || '20px',
                grid_width: presetValues.grid_width || '100%',
                product_background: presetValues.product_background || '#ffffff',
                product_content_padding: presetValues.product_content_padding || '15',
                product_title: presetValues.product_title || '#0170B9',
                product_title_hover_color: presetValues.product_title_hover_color || '#015293',
                title_size: presetValues.title_size || '16px',
                title_weight: presetValues.title_weight || '600',
                description_color: presetValues.description_color || '#23282d',
                desc_size: presetValues.desc_size || '14px',
                price_delete_color: presetValues.price_delete_color || '#333333',
                price_color: presetValues.price_color || '#0170B9',
                price_size: presetValues.price_size || '18px',
                price_weight: presetValues.price_weight || '700',
                star_size: presetValues.star_size || '14px',
                star_color: presetValues.star_color || '#ffc107',
                text_align: presetValues.text_align || 'left',
                border_radius: presetValues.border_radius || '4px',
                border_style: presetValues.border_style || 'solid',
                border_width: presetValues.border_width || '1px',
                border_color: presetValues.border_color || '#eeeeee',
                product_image_width: presetValues.product_image_width || '100%',
                product_image_height: presetValues.product_image_height || 'auto',
                image_aspect_ratio: presetValues.image_aspect_ratio || '1:1',
                product_badge_background: presetValues.product_badge_background || 'rgb(54, 182, 217)',
                product_badge_font_color: presetValues.product_badge_font_color || '#ffffff',
                product_badge_font_size: presetValues.product_badge_font_size || '12px',
                product_badge_font_weight: presetValues.product_badge_font_weight || '400',
                product_badge_text_align: presetValues.product_badge_text_align || 'center',
                product_badge_text_transform: presetValues.product_badge_text_transform || 'none',
                product_badge_border_radius: presetValues.product_badge_border_radius || '20px',
                product_badge_padding: presetValues.product_badge_padding || '5px',
                product_badge_margin: presetValues.product_badge_margin || '0px',
                button_border_radius: presetValues.button_border_radius || '4px',
                button_bg_color: presetValues.button_bg_color || '#0170B9',
                button_text_color: presetValues.button_text_color || '#ffffff',
                button_hover_bg: presetValues.button_hover_bg || '#015293',
                button_hover_text_color: presetValues.button_hover_text_color || '#ffffff',
                button_font_size: presetValues.button_font_size || '14px',
                button_padding: presetValues.button_padding || '8px 12px',
                button_margin: presetValues.button_margin || '0px',
                // Additional properties
                custom_class: ''
            };

            setEditingShowcase(newShowcase);
            setCurrentView('editor');
            updateURL('editor', { create: 'true' });

        } catch (error) {
            console.error('Error loading preset values:', error);

            // Fallback to basic defaults if preset loading fails
            const newShowcase = {
                id: '',
                layout,
                proddisp_layout_mode: mode,
                name: name || `New Showcase - ${new Date().toLocaleString()}`,
                product_source: 'specific',
                products: [],
                limit: 4,
                columns: 4,
                orderby: 'date',
                order: 'DESC',
                show_title: 'yes',
                show_price: 'yes',
                show_rating: 'yes',
                show_description: 'no',
                show_addtocart: 'yes',
                custom_class: ''
            };

            setEditingShowcase(newShowcase);
            setCurrentView('editor');
            updateURL('editor', { create: 'true' });
        }
    };

    const handleSave = async () => {
        await loadShowcases();
    };

    const handleDelete = async (showcaseId) => {
        try {
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_delete_showcase',
                    nonce: proddispAdmin.nonce,
                    showcase_id: showcaseId
                })
            });

            const data = await response.json();
            if (data.success) {
                await loadShowcases();
                return true; // Success
            } else {
                console.error('Error deleting showcase:', data.data?.message || 'Unknown error');
                return false; // Failure
            }
        } catch (error) {
            console.error('Error deleting showcase:', error);
            return false; // Failure
        }
    };

    const renderCurrentView = () => {
        switch (currentView) {
            case 'layout-selector':
                return (
                    <LayoutSelector
                        onLayoutSelected={handleLayoutSelected}
                        onBack={() => setCurrentView('list')}
                    />
                );
            case 'editor':
                return (
                    <ShowcaseEditor
                        showcase={editingShowcase}
                        onSave={handleSave}
                        onCancel={() => setCurrentView('list')}
                    />
                );
            case 'shortcode-generator':
                return (
                    <ShortcodeGenerator
                        onBack={() => setCurrentView('list')}
                    />
                );
            case 'get-started':
                return (
                    <GetStarted
                        onBack={() => {
                            setCurrentView('list');
                            updateURL('list');
                        }}
                        onCreateNew={() => {
                            handleCreateNew();
                        }}
                        onShowShortcodeGenerator={() => {
                            setCurrentView('shortcode-generator');
                            updateURL('shortcode-generator');
                        }}
                    />
                );
            default:
                return (
                    <ShowcaseList
                        showcases={showcases}
                        loading={loading}
                        onCreateNew={handleCreateNew}
                        onEdit={handleEdit}
                        onDelete={handleDelete}
                        onDuplicate={handleDuplicate}
                        onShowShortcodeGenerator={() => setCurrentView('shortcode-generator')}
                        onShowGetStarted={() => {
                            setCurrentView('get-started');
                            updateURL('get-started');
                        }}
                    />
                );
        }
    };

    console.log('Rendering App with currentView:', currentView);
    return (
        <div className="wcps-admin-styles">
            {renderCurrentView()}
            <ToastContainer />
        </div>
    );
};

export default App;