// src/Admin/components/MigrationComponent.jsx
import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import ecreIcons from '../../components/core/icons';
import SupportPopup from '../../components/core/SupportPopup';
import useSupportPopup from '../../hooks/useSupportPopup';
import { translate } from '../../Helper';

const MigrationComponent = () => {
    const [migrationState, setMigrationState] = useState({
        isActive: false,
        isPaused: false,
        isCompleted: false,
        progress: 0,
        currentStep: '',
        totalOrders: 0,
        processedOrders: 0,
        migratedReferrals: 0,
        migratedRewards: 0,
        migratedCoupons: 0,
        migratedReferrers: 0,
        errors: [],
        startTime: null,
        estimatedTimeRemaining: 0
    });
    
    const [showMigration, setShowMigration] = useState(false);
    const [migrationDetails, setMigrationDetails] = useState(null);
    const intervalRef = useRef(null);
    const abortControllerRef = useRef(null);
    const [expanded, setExpanded] = useState(false);

    // Support popup functionality
    const {
        isOpen: isSupportModal,
        openSupportPopup,
        closeSupportPopup,
        handleEmailRedirect,
        handleCopy,
        copiedItemIndex,
        error,
        clearError
    } = useSupportPopup();

    // Check if migration is needed on component mount
    useEffect(() => {
        checkMigrationStatus();
        
        // Check for existing migration process
        const savedState = localStorage.getItem('ecre_migration_state');
        if (savedState) {
            const parsedState = JSON.parse(savedState);
            if (parsedState.isActive && !parsedState.isCompleted) {
                setMigrationState(parsedState);
                setShowMigration(true);
                startProgressPolling();
            }
        }
        
        return () => {
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
            }
            if (abortControllerRef.current) {
                abortControllerRef.current.abort();
            }
        };
    }, []);

    // Save migration state to localStorage
    useEffect(() => {
        if (migrationState.isActive || migrationState.isCompleted) {
            localStorage.setItem('ecre_migration_state', JSON.stringify(migrationState));
        }
    }, [migrationState]);

    const checkMigrationStatus = async () => {
        try {
            const formData = new FormData();
            formData.append('action', 'ecre_check_migration_needed');
            formData.append('nonce', ecreAdmin.nonce);

            const response = await axios.post(ecreAdmin.ajaxurl, formData);
            
            if (response.data.success) {
                const { needsMigration, oldDataCount, isNoticeDismissed } = response.data.data;
                
                // Don't show if user has dismissed the notice
                if (isNoticeDismissed) {
                    return;
                }
                
                if (needsMigration && oldDataCount.orders > 0) {
                    setShowMigration(true);
                    setMigrationDetails({
                        totalOrders: oldDataCount.orders,
                        totalCoupons: oldDataCount.coupons,
                        totalUsers: oldDataCount.users
                    });
                }
            }
        } catch (error) {
            console.error('Error checking migration status:', error);
        }
    };

    const startMigration = async () => {
        try {
            abortControllerRef.current = new AbortController();
            
            const formData = new FormData();
            formData.append('action', 'ecre_start_migration');
            formData.append('nonce', ecreAdmin.nonce);

            setMigrationState(prev => ({
                ...prev,
                isActive: true,
                isPaused: false,
                isCompleted: false,
                startTime: Date.now(),
                currentStep: 'Initializing migration...',
                errors: []
            }));

            const response = await axios.post(ecreAdmin.ajaxurl, formData, {
                signal: abortControllerRef.current.signal
            });

            if (response.data.success) {
                const { migrationId, totalItems } = response.data.data;
                
                // FIXED: Update state and start polling in the same operation
                setMigrationState(prev => {
                    const newState = {
                        ...prev,
                        totalOrders: totalItems,
                        migrationId: migrationId
                    };
                    
                    // Start polling immediately with the migration ID
                    setTimeout(() => startProgressPollingWithId(migrationId), 1000);
                    
                    return newState;
                });
            } else {
                throw new Error(response.data.data?.message || 'Failed to start migration');
            }
        } catch (error) {
            if (error.name !== 'AbortError') {
                setMigrationState(prev => ({
                    ...prev,
                    isActive: false,
                    errors: [...prev.errors, `Migration start failed: ${error.message}`]
                }));
            }
        }
    };

    // NEW: Progress polling function that takes migration ID as parameter
    const startProgressPollingWithId = (migrationId) => {
        if (intervalRef.current) {
            clearInterval(intervalRef.current);
        }
        
        intervalRef.current = setInterval(() => checkMigrationProgressWithId(migrationId), 1000);
    };

    // NEW: Progress check function that takes migration ID as parameter
    const checkMigrationProgressWithId = async (migrationId) => {
        try {

            if (!migrationId) {
                return;
            }

            const formData = new FormData();
            formData.append('action', 'ecre_get_migration_progress');
            formData.append('nonce', ecreAdmin.nonce);
            formData.append('migration_id', migrationId);

            const response = await axios.post(ecreAdmin.ajaxurl, formData);
            

            if (response.data.success) {
                const progress = response.data.data;
                         
                setMigrationState(prev => {
                    const newState = {
                        ...prev,
                        ...progress,
                        // Calculate progress - if total_orders is 0, set to 100% when completed
                        progress: progress.status === 'completed' ? 100 : 
                                (progress.total_orders > 0 ? 
                                Math.round((progress.processed_orders / progress.total_orders) * 100) : 0)
                    };
                    
                    return newState;
                });
                
                // Check if migration is completed
                if (progress.status === 'completed') {
                    if (intervalRef.current) {
                        clearInterval(intervalRef.current);
                    }
                    
                    setMigrationState(prev => ({
                        ...prev,
                        isActive: false,
                        isCompleted: true,
                        progress: 100,
                        currentStep: 'Migration completed successfully!'
                    }));
                    
                }
            }
        } catch (error) {
            console.error('Error checking migration progress:', error);
        }
    };

    const pauseMigration = async () => {
        try {
            const formData = new FormData();
            formData.append('action', 'ecre_pause_migration');
            formData.append('nonce', ecreAdmin.nonce);
            formData.append('migration_id', migrationState.migrationId);

            await axios.post(ecreAdmin.ajaxurl, formData);
            
            setMigrationState(prev => ({
                ...prev,
                isPaused: true,
                currentStep: 'Migration paused'
            }));
            
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
            }
        } catch (error) {
            console.error('Error pausing migration:', error);
        }
    };

    const resumeMigration = async () => {
        try {
            const formData = new FormData();
            formData.append('action', 'ecre_resume_migration');
            formData.append('nonce', ecreAdmin.nonce);
            formData.append('migration_id', migrationState.migrationId);

            const response = await axios.post(ecreAdmin.ajaxurl, formData);
            
            if (response.data.success) {
                setMigrationState(prev => ({
                    ...prev,
                    isPaused: false,
                    currentStep: 'Resuming migration...'
                }));
                
                startProgressPolling();
            }
        } catch (error) {
            console.error('Error resuming migration:', error);
        }
    };

    const cancelMigration = async () => {
        try {
            const formData = new FormData();
            formData.append('action', 'ecre_cancel_migration');
            formData.append('nonce', ecreAdmin.nonce);
            formData.append('migration_id', migrationState.migrationId);

            await axios.post(ecreAdmin.ajaxurl, formData);
            
            if (abortControllerRef.current) {
                abortControllerRef.current.abort();
            }
            
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
            }
            
            setMigrationState(prev => ({
                ...prev,
                isActive: false,
                isPaused: false,
                currentStep: 'Migration cancelled'
            }));
            
            localStorage.removeItem('ecre_migration_state');
        } catch (error) {
            console.error('Error cancelling migration:', error);
        }
    };

    const startProgressPolling = () => {
        if (intervalRef.current) {
            clearInterval(intervalRef.current);
        }
        
        // Poll more frequently to catch quick completions
        intervalRef.current = setInterval(checkMigrationProgress, 1000); // Changed from 2000 to 1000
    };

    const checkMigrationProgress = async () => {
        try {
            const formData = new FormData();
            formData.append('action', 'ecre_get_migration_progress');
            formData.append('nonce', ecreAdmin.nonce);
            formData.append('migration_id', migrationState.migrationId);

            const response = await axios.post(ecreAdmin.ajaxurl, formData);
            
            if (response.data.success) {
                const progress = response.data.data;
                             
                setMigrationState(prev => {
                    const newState = {
                        ...prev,
                        ...progress,
                        // Calculate progress - if total_orders is 0, set to 100% when completed
                        progress: progress.status === 'completed' ? 100 : 
                                (progress.total_orders > 0 ? 
                                Math.round((progress.processed_orders / progress.total_orders) * 100) : 0)
                    };
                    
                    // Calculate estimated time remaining
                    if (prev.startTime && progress.processed_orders > 0 && progress.status !== 'completed') {
                        const elapsed = Date.now() - prev.startTime;
                        const rate = progress.processed_orders / elapsed;
                        const remaining = progress.total_orders - progress.processed_orders;
                        newState.estimatedTimeRemaining = Math.round(remaining / rate);
                    }
                    
                    return newState;
                });
                
                // Check if migration is completed
                if (progress.status === 'completed') {
                    if (intervalRef.current) {
                        clearInterval(intervalRef.current);
                    }
                    
                    setMigrationState(prev => ({
                        ...prev,
                        isActive: false,
                        isCompleted: true,
                        progress: 100,
                        currentStep: 'Migration completed successfully!'
                    }));
    
                }
            }
        } catch (error) {
            console.error('Error checking migration progress:', error);
        }
    };

    const formatTime = (milliseconds) => {
        const seconds = Math.floor(milliseconds / 1000);
        const minutes = Math.floor(seconds / 60);
        const hours = Math.floor(minutes / 60);
        
        if (hours > 0) {
            return `${hours}h ${minutes % 60}m`;
        } else if (minutes > 0) {
            return `${minutes}m ${seconds % 60}s`;
        } else {
            return `${seconds}s`;
        }
    };

    const dismissMigration = async () => {
        try {
            const formData = new FormData();
            formData.append('action', 'ecre_dismiss_migration_notice');
            formData.append('nonce', ecreAdmin.nonce);

            await axios.post(ecreAdmin.ajaxurl, formData);
        } catch (error) {
            console.error('Error dismissing migration notice:', error);
        }
        
        // Hide locally regardless
        setShowMigration(false);
        localStorage.removeItem('ecre_migration_state');
    };

    if (!showMigration) {
        return null;
    }

    return (
        <div className="ecre-data-migration ecre-p-4 ecre-mb-6 ecre-bg-white ecre-rounded-lg ecre-border ecre-border-gray-200">
            <div className="ecre-flex ecre-justify-between ecre-items-center ecre-gap-5">
                <div className="ecre-flex ecre-items-center ecre-text-sm ecre-text-gray-900 ecre-font-medium ecre-gap-2">
                    {(migrationState.isActive || migrationState.isPaused || migrationState.isCompleted) }
                    <span className="icon ecre-leading-[0px]">
                        {migrationState.isActive && !migrationState.isPaused
                            ? ecreIcons.spin
                            : migrationState.errors.length > 0
                            ? ecreIcons.alert
                            : migrationState.isCompleted
                            ? ecreIcons.circleCheck
                            : ecreIcons.dbMigration 
                        }
                    </span> 
                    <span>
                        {migrationState.isActive && !migrationState.isPaused
                            ? `${ translate( 'migrating_data' ) } (${migrationState.progress}%)`
                            : migrationState.errors.length > 0
                            ? translate( 'migration_failed' )
                            : migrationState.isCompleted
                            ? translate( 'data_migration_completed' )
                            : translate( 'migrate_data_unlock_features' )
                        }
                    </span>
                </div>
                {expanded == false ? (
                    <div onClick={()=> setExpanded(!expanded)} className="ecre-text-[#6A40D5] ecre-text-sm ecre-font-medium ecre-cursor-pointer">
                        { translate( 'view_more' ) }
                        <span className="ecre-ml-1.5 ecre-transform -ecre-translate-y-1/2 ecre-text-gray-900 ecre-w-5 ecre-h-5">
                            <svg xmlns="http://www.w3.org/2000/svg" width="12" height="8" viewBox="0 0 12 8" fill="none">
                                <path d="M11 1.5L6 6.5L1 1.5" stroke="#6A40D5" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                            </svg>
                        </span>
                    </div>
                ) : null}
            </div>

            <div className={`ecre-grid ecre-text-sm ecre-text-slate-600 ecre-overflow-hidden ecre-transition-all ecre-duration-300 ecre-ease-in-out ${expanded ? 'ecre-grid-rows-[1fr] ecre-opacity-100' : 'ecre-grid-rows-[0fr] ecre-opacity-0'}`}>
                <div className="ecre-overflow-hidden">
                    <div className="ecre-text-gray-500 ecre-text-sm ecre-font-normal ecre-mt-1.5">
                        {migrationState.isActive && !migrationState.isPaused
                            ? translate( 'migrating_data_desc' )
                            : migrationState.errors.length > 0
                            ? translate( 'migration_failed_desc' )
                            : migrationState.isCompleted
                            ? translate( 'migration_completed_desc' )
                            : translate( 'migrate_data_unlock_features_desc' )
                        }
                        
                    </div>
                    <div className="ecre-flex ecre-flex-wrap ecre-justify-end ecre-items-center ecre-gap-3 ecre-mt-3">
                        {migrationState.isActive && !migrationState.isPaused
                            ?   <>
                                    <button onClick={cancelMigration} className="ecre-cursor-pointer ecre-px-4 ecre-py-2 ecre-bg-white ecre-rounded ecre-border ecre-border-violet-700 ecre-text-violet-700 ecre-text-sm ecre-font-semibold ecre-transition-all hover:ecre-bg-violet-700 hover:ecre-text-white">{ translate( 'cancel' ) }</button>
                                    <button onClick={()=> setExpanded(!expanded)} className="ecre-cursor-pointer ecre-px-4 ecre-py-2 ecre-bg-slate-100 ecre-rounded ecre-border ecre-border-slate-100 ecre-text-gray-900 ecre-text-sm ecre-font-semibold ecre-transition-all hover:ecre-bg-slate-300">{ translate( 'minimize' ) }</button>
                                </>
                            : migrationState.errors.length > 0
                            ?   <>
                                    <button onClick={startMigration} className="ecre-cursor-pointer ecre-px-4 ecre-py-2 ecre-bg-white ecre-rounded ecre-border ecre-border-violet-700 ecre-text-violet-700 ecre-text-sm ecre-font-semibold ecre-transition-all hover:ecre-bg-violet-700 hover:ecre-text-white">{ translate( 'restart_migration' ) }</button>
                                    <button onClick={openSupportPopup} className="ecre-outline-0 ecre-cursor-pointer ecre-px-4 ecre-py-2 ecre-bg-orange-50 ecre-rounded ecre-border ecre-border-orange-50 ecre-text-amber-800 ecre-text-sm ecre-font-semibold ecre-transition-all hover:ecre-bg-orange-100">{ translate( 'contact_support' ) }</button>
                                    <button onClick={()=> setExpanded(!expanded)} className="ecre-cursor-pointer ecre-px-4 ecre-py-2 ecre-bg-slate-100 ecre-rounded ecre-border ecre-border-slate-100 ecre-text-gray-900 ecre-text-sm ecre-font-semibold ecre-transition-all hover:ecre-bg-slate-300">{ translate( 'minimize' ) }</button>
                                </>
                            : migrationState.isCompleted
                            ? <button onClick={dismissMigration} className="ecre-cursor-pointer ecre-px-4 ecre-py-2 ecre-bg-white ecre-rounded ecre-border ecre-border-violet-700 ecre-text-violet-700 ecre-text-sm ecre-font-semibold ecre-transition-all hover:ecre-bg-violet-700 hover:ecre-text-white">{ translate( 'close_notice' ) }</button>
                            :   <>
                                    <button onClick={startMigration} className="ecre-cursor-pointer ecre-px-4 ecre-py-2 ecre-bg-violet-700 ecre-rounded ecre-border ecre-border-violet-700 ecre-text-white ecre-text-sm ecre-font-semibold ecre-transition-all hover:ecre-bg-white hover:ecre-text-violet-700">{ translate( 'start_migration' ) }</button>
                                    <button onClick={()=> setExpanded(!expanded)} className="ecre-cursor-pointer ecre-px-4 ecre-py-2 ecre-bg-slate-100 ecre-rounded ecre-border ecre-border-slate-100 ecre-text-gray-900 ecre-text-sm ecre-font-semibold ecre-transition-all hover:ecre-bg-slate-300">{ translate( 'do_it_later' ) }</button>
                                </>
                        }
                    </div>
                </div>
            </div>

            <SupportPopup
                isOpen={isSupportModal}
                onClose={closeSupportPopup}
                onEmailRedirect={handleEmailRedirect}
                onCopy={handleCopy}
                copiedItemIndex={copiedItemIndex}
                error={error}
                onClearError={clearError}
            />
        </div>
    );
};

export default MigrationComponent;