import { useState, useEffect, useRef } from '@wordpress/element';
import { createPortal } from '@wordpress/element';
import { SelectControl } from '@wordpress/components';
import './ArchivedDataFilter.scss';

const ArchivedDataFilter = ({ restUrl, nonce, syncEnabled, ajaxUrl }) => {
    const [filterMode, setFilterMode] = useState('exclude');
    const [loading, setLoading] = useState(true);
    const [container, setContainer] = useState(null);
    const [backfillRunning, setBackfillRunning] = useState(true);
    const [backfillProgress, setBackfillProgress] = useState(0);
    const [backfillStatus, setBackfillStatus] = useState(null);
    const pollingRef = useRef(null);
    
    // Check if sync is enabled (show filter only if enabled)
    // Values can be: true, 'auto', '1', or truthy values = enabled
    // Values can be: false, '0', '', null, undefined = disabled
    const isSyncEnabled = syncEnabled === true || 
                          syncEnabled === 'auto' || 
                          syncEnabled === '1' || 
                          syncEnabled === 1 ||
                          (typeof syncEnabled === 'string' && syncEnabled.toLowerCase() === 'true');

    // Fetch current filter mode from WordPress
    useEffect(() => {
        const fetchFilterMode = async () => {
            try {
                const response = await fetch(`${restUrl}archm/v1/analytics-filter`, {
                    headers: {
                        'X-WP-Nonce': nonce
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    if (data.mode) {
                        setFilterMode(data.mode);
                        // Also store in localStorage for quick access
                        localStorage.setItem('archm_analytics_filter_mode', data.mode);
                    }
                }
            } catch (error) {
                console.error('Failed to fetch filter mode:', error);
                // Fallback to localStorage if available
                const stored = localStorage.getItem('archm_analytics_filter_mode');
                if (stored) {
                    setFilterMode(stored);
                }
            } finally {
                setLoading(false);
            }
        };

        fetchFilterMode();
    }, [restUrl, nonce]);

    // Check backfill status and poll progress
    useEffect(() => {
        if (!isSyncEnabled) {
            setBackfillRunning(false);
            if (pollingRef.current) {
                clearInterval(pollingRef.current);
                pollingRef.current = null;
            }
            return;
        }

        // Fetch backfill progress via AJAX
        const fetchBackfillProgress = async () => {
            try {
                const formData = new FormData();
                formData.append('action', 'check_analytics_backfill_progress');
                formData.append('nonce', nonce);

                const response = await fetch(ajaxUrl, {
                    method: 'POST',
                    body: formData
                });

                console.log('ArchivedDataFilter: Backfill progress response:', response);

                if (response.ok) {
                    const data = await response.json();
                    console.log('ArchivedDataFilter: Backfill progress data:', data);
                    if (data.success && data.data) {
                        const progress = parseInt(data.data.progress || 0, 10);
                        const status = data.data.status || 'processing';
                        
                        setBackfillProgress(progress);
                        setBackfillStatus(status);

                        // Check if backfill is actually running
                        const isRunning = status === 'processing' && progress < 100;
                        setBackfillRunning(isRunning);

                        // If completed or cancelled, stop polling
                        if (status === 'completed' || status === 'cancelled' || progress >= 100) {
                            setBackfillRunning(false);
                            if (pollingRef.current) {
                                clearInterval(pollingRef.current);
                                pollingRef.current = null;
                            }
                            return false; // Stop polling
                        }
                        return true; // Continue polling
                    } else {
                        // No valid data means backfill is not running
                        setBackfillRunning(false);
                        if (pollingRef.current) {
                            clearInterval(pollingRef.current);
                            pollingRef.current = null;
                        }
                        return false;
                    }
                } else {
                    // Error means backfill is not running
                    setBackfillRunning(false);
                    if (pollingRef.current) {
                        clearInterval(pollingRef.current);
                        pollingRef.current = null;
                    }
                    return false;
                }
            } catch (error) {
                console.error('Failed to fetch backfill progress:', error);
                setBackfillRunning(false);
                if (pollingRef.current) {
                    clearInterval(pollingRef.current);
                    pollingRef.current = null;
                }
                return false;
            }
        };

        // Initial check
        fetchBackfillProgress().then((continuePolling) => {
            if (continuePolling === true) {
                // Start polling if backfill is running
                pollingRef.current = setInterval(async () => {
                    const shouldContinue = await fetchBackfillProgress();
                    if (shouldContinue === false) {
                        if (pollingRef.current) {
                            clearInterval(pollingRef.current);
                            pollingRef.current = null;
                        }
                    }
                }, 2000);
            }
        });

        return () => {
            if (pollingRef.current) {
                clearInterval(pollingRef.current);
                pollingRef.current = null;
            }
        };
    }, [restUrl, nonce, isSyncEnabled, ajaxUrl]);

    // Find the filter container in WooCommerce Analytics page
    // This effect runs continuously to handle SPA navigation
    useEffect(() => {
        // Don't insert filter if sync is not enabled
        if (!isSyncEnabled) {
            // Remove filter if it exists
            const existingFilter = document.querySelector('.woocommerce-filters-filter.archm-archived-data-filter-wrapper');
            if (existingFilter && existingFilter.parentElement) {
                existingFilter.parentElement.removeChild(existingFilter);
            }
            setContainer(null);
            return;
        }
        
        const findAndInsertFilter = () => {
            // Check if our filter already exists to avoid duplicates
            const existingFilter = document.querySelector('.woocommerce-filters-filter.archm-archived-data-filter-wrapper');
            if (existingFilter) {
                setContainer(existingFilter);
                return true;
            }

            // Target the exact container from the screenshot: .woocommerce-filters__basic-filters
            // Note: Double underscore (__) is the correct BEM naming convention
            // This is the flex container that holds all filter elements
            const basicFiltersContainer = document.querySelector('.woocommerce-filters__basic-filters');
            
            if (!basicFiltersContainer) {
                return false;
            }

            // Check if we're on an Analytics page (not other WooCommerce pages)
            // Look for Analytics-specific indicators
            const isAnalyticsPage = window.location.href.includes('/analytics/') || 
                                   document.querySelector('.woocommerce-layout__primary') ||
                                   document.querySelector('.woocommerce-filters__basic-filters');
            
            if (!isAnalyticsPage) {
                return false;
            }

            console.log('ArchivedDataFilter: Found .woocommerce-filters__basic-filters container');

            // Create a wrapper div matching WooCommerce's filter structure
            // Use the same class as existing filters: .woocommerce-filters-filter
            const wrapper = document.createElement('div');
            wrapper.className = 'woocommerce-filters-filter archm-archived-data-filter-wrapper';
            
            // Set CSS order property to ensure consistent positioning
            // This prevents position changes when WooCommerce re-renders filters after date updates
            wrapper.style.order = '999';
            
            // Insert as the last child of the flex container (after Date range and Show filters)
            // CSS order property will ensure it stays in the correct position even after re-renders
            basicFiltersContainer.appendChild(wrapper);
            
            console.log('ArchivedDataFilter: Inserted filter into .woocommerce-filters__basic-filters');
            
            setContainer(wrapper);
            return true;
        };

        // Try to find and insert immediately
        let inserted = findAndInsertFilter();
        let intervalId = null;
        let observer = null;
        let lastUrl = window.location.href;
        
        // Continuous interval to check for filter container (handles SPA navigation)
        intervalId = setInterval(() => {
            // Don't do anything if sync is not enabled
            if (!isSyncEnabled) {
                // Remove filter if it exists
                const existingFilter = document.querySelector('.woocommerce-filters-filter.archm-archived-data-filter-wrapper');
                if (existingFilter && existingFilter.parentElement) {
                    existingFilter.parentElement.removeChild(existingFilter);
                }
                setContainer(null);
                inserted = false;
                return;
            }
            
            // Check if URL changed (SPA navigation)
            const currentUrl = window.location.href;
            if (currentUrl !== lastUrl) {
                lastUrl = currentUrl;
                // Reset container on navigation
                setContainer(null);
                inserted = false;
            }
            
            // Check if container still exists
            const currentContainer = document.querySelector('.woocommerce-filters-filter.archm-archived-data-filter-wrapper');
            if (!currentContainer) {
                inserted = false;
            }
            
            // Try to insert if not already inserted
            if (!inserted) {
                inserted = findAndInsertFilter();
            }
        }, 300);

        // MutationObserver to watch for DOM changes (handles React re-renders)
        // Use debounce to avoid rapid re-insertions during WooCommerce re-renders
        let reinsertTimeout = null;
        const debouncedReinsert = () => {
            if (reinsertTimeout) {
                clearTimeout(reinsertTimeout);
            }
            reinsertTimeout = setTimeout(() => {
                if (!isSyncEnabled) {
                    return;
                }
                const currentContainer = document.querySelector('.woocommerce-filters-filter.archm-archived-data-filter-wrapper');
                if (!currentContainer) {
                    const basicFiltersContainer = document.querySelector('.woocommerce-filters__basic-filters');
                    if (basicFiltersContainer) {
                        // Wait a bit more to ensure WooCommerce has finished re-rendering
                        setTimeout(() => {
                            inserted = findAndInsertFilter();
                        }, 100);
                    } else {
                        setContainer(null);
                        inserted = false;
                    }
                }
            }, 200); // Debounce delay to wait for WooCommerce re-render to complete
        };

        observer = new MutationObserver((mutations) => {
            // Don't do anything if sync is not enabled
            if (!isSyncEnabled) {
                return;
            }
            
            // Check if our filter was removed
            const currentContainer = document.querySelector('.woocommerce-filters-filter.archm-archived-data-filter-wrapper');
            if (!currentContainer) {
                // Use debounced re-insertion to avoid rapid re-insertions during re-renders
                debouncedReinsert();
            }
            
            // Also check if basic filters container was added (new page loaded)
            mutations.forEach((mutation) => {
                mutation.addedNodes.forEach((node) => {
                    if (node.nodeType === 1) { // Element node
                        // Check if the added node or its children contain the filters container
                        if (node.querySelector && node.querySelector('.woocommerce-filters__basic-filters')) {
                            if (!inserted) {
                                debouncedReinsert();
                            }
                        }
                        // Check if the node itself is the filters container
                        if (node.classList && node.classList.contains('woocommerce-filters__basic-filters')) {
                            if (!inserted) {
                                debouncedReinsert();
                            }
                        }
                    }
                });
            });
        });

        // Observe the entire document for changes
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });

        // Also listen for navigation events (SPA navigation)
        const handleNavigation = () => {
            setContainer(null);
            inserted = false;
            // Wait a bit for React to render the new page
            setTimeout(() => {
                inserted = findAndInsertFilter();
            }, 500);
        };

        // Listen for various navigation events
        window.addEventListener('hashchange', handleNavigation);
        window.addEventListener('popstate', handleNavigation);
        
        // Intercept pushState/replaceState for SPA navigation detection
        const originalPushState = history.pushState;
        const originalReplaceState = history.replaceState;
        
        const pushStateHandler = function(...args) {
            originalPushState.apply(history, args);
            handleNavigation();
        };
        
        const replaceStateHandler = function(...args) {
            originalReplaceState.apply(history, args);
            handleNavigation();
        };
        
        history.pushState = pushStateHandler;
        history.replaceState = replaceStateHandler;

        // Cleanup function
        return () => {
            if (intervalId) {
                clearInterval(intervalId);
            }
            if (observer) {
                observer.disconnect();
            }
            if (reinsertTimeout) {
                clearTimeout(reinsertTimeout);
            }
            window.removeEventListener('hashchange', handleNavigation);
            window.removeEventListener('popstate', handleNavigation);
            // Restore original history methods
            if (history.pushState === pushStateHandler) {
                history.pushState = originalPushState;
            }
            if (history.replaceState === replaceStateHandler) {
                history.replaceState = originalReplaceState;
            }
            // Remove filter element if sync is disabled
            if (!isSyncEnabled) {
                const filterElement = document.querySelector('.woocommerce-filters-filter.archm-archived-data-filter-wrapper');
                if (filterElement && filterElement.parentElement) {
                    filterElement.parentElement.removeChild(filterElement);
                }
            }
        };
    }, [isSyncEnabled]);

    // Handle filter mode change
    const handleFilterChange = async (newMode) => {
        setFilterMode(newMode);
        
        // Store in localStorage immediately for quick access
        localStorage.setItem('archm_analytics_filter_mode', newMode);

        // Update WordPress option via REST API
        try {
            const response = await fetch(`${restUrl}archm/v1/analytics-filter`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                },
                body: JSON.stringify({ mode: newMode })
            });

            if (!response.ok) {
                console.error('Failed to update filter mode');
                // Revert on error
                const previous = localStorage.getItem('archm_analytics_filter_mode') || 'combine';
                setFilterMode(previous);
            } else {
                // Trigger analytics refresh by dispatching a custom event
                // WooCommerce Admin listens for certain events to refresh data
                window.dispatchEvent(new CustomEvent('archm_analytics_filter_changed', {
                    detail: { mode: newMode }
                }));

                // Try to trigger WooCommerce's refresh mechanism
                // WooCommerce Admin uses React Query, so we might need to invalidate queries
                if (window.wc && window.wc.data && window.wc.data.dispatch) {
                    try {
                        // Try to invalidate analytics queries
                        const store = window.wc.data.dispatch('wc/admin');
                        if (store && typeof store.invalidateResolution === 'function') {
                            store.invalidateResolution('getReportStats');
                        }
                    } catch (e) {
                        // If that doesn't work, try alternative approach
                        console.log('Could not invalidate queries directly');
                    }
                }

                // Reload the page to refresh analytics data
                // This ensures the filter change is immediately reflected
                setTimeout(() => {
                    window.location.reload();
                }, 300);
            }
        } catch (error) {
            console.error('Error updating filter mode:', error);
            // Revert on error
            const previous = localStorage.getItem('archm_analytics_filter_mode') || 'exclude';
            setFilterMode(previous);
        }
    };

    // Don't render if sync is not enabled
    if (!isSyncEnabled) {
        return null;
    }
    
    // Don't render until container is found
    if (!container || loading) {
        return null;
    }

    const filterOptions = [
        { label: 'Exclude archived data', value: 'exclude' },
        { label: 'Combine archived and current WooCommerce orders data', value: 'combine' },
        { label: 'Archived data only', value: 'archived_only' },
    ];

    return createPortal(
        <div className="archm-archived-data-filter">
            <span className="woocommerce-filters-label">Archived Data Analytics:</span>
            <div className="woocommerce-dropdown-button_labels">
                <div className="archm-filter-wrapper" style={{ position: 'relative', width: '100%' }}>
                    <SelectControl
                        value={filterMode}
                        options={filterOptions}
                        onChange={handleFilterChange}
                        className="archm-filter-select"
                        disabled={backfillRunning}
                    />
                    {backfillRunning && (
                        <div className="archm-backfill-loader-overlay">
                            <div className="archm-backfill-loader-content">
                                <div className="archm-backfill-spinner">
                                    <svg className="archm-spinner-svg" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <circle className="archm-spinner-circle" cx="12" cy="12" r="10" stroke="#0073aa" strokeWidth="2" fill="none"/>
                                    </svg>
                                </div>
                                <div className="archm-backfill-text">
                                    <span className="archm-backfill-message">Loading Archived Data...</span>
                                    <span className="archm-backfill-percentage">{backfillProgress}%</span>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>,
        container
    );
};

export default ArchivedDataFilter;

