import React, { createContext, useRef, useContext, useState, useEffect } from 'react';
import { IonContent, IonPage, IonToast } from '@ionic/react';
import { useHistory } from 'react-router-dom';
import { Keyboard } from "@capacitor/keyboard";
import { App } from '@capacitor/app';

const FunctionContext = createContext<{
    registerFunction: (name: string, fn: (...args: any[]) => any) => void;
    callFunction: (name: string, ...args: any[]) => any;
    showToast: (message: string, duration?: number) => void;
} | null>(null);

const Layout: React.FC<{ title?: string; children: React.ReactNode }> = ({ title, children }) => {
    const history = useHistory(); // ✅ React Router history
    const functionRegistry = useRef<{ [key: string]: (...args: any[]) => any }>({});
    const [toastMessage, setToastMessage] = useState<string>('');
    const [toastVisible, setToastVisible] = useState<boolean>(false);

    // ✅ Handle App State Changes (e.g., when app resumes)
    useEffect(() => {
        let appStateListener;

        const setupAppStateListener = async () => {
            appStateListener = await App.addListener('appStateChange', (state) => {
                if (state.isActive) {
                    callFunction('updateChatUser');
                    callFunction('updateChatDriver');
                }
            });
        };

        setupAppStateListener();

        return () => {
            if (appStateListener) appStateListener.remove();
        };
    }, []);

    // ✅ Handle Android Hardware Back Button (Pop History)
    useEffect(() => {
        let backButtonListener;

        const setupBackButtonListener = async () => {
            backButtonListener = await App.addListener('backButton', () => {
                console.log('Back button pressed');
        
                if (history.length > 1) {
                    alert('** Utiliza la navegación de la app para navegar hacia atrás');
        
                    // ✅ Reset navigation stack by forcing a new navigation entry
                    history.replace('/');
        
                    setTimeout(() => {
                        window.location.replace('/'); // ✅ Hard reset to prevent back navigation
                    }, 100); // Small delay ensures correct execution order
                } else {
                    console.log('Already at home, preventing back navigation.');
                }
            });
        };
        setupBackButtonListener();

        return () => {
            if (backButtonListener) backButtonListener.remove();
        };
    }, [history]);

    // ✅ Initialize local storage settings
    useEffect(() => {
        localStorage.serverPath = 'https://dash.coinpler.com/ws/wsMain.php';
        localStorage.serverPathV2 = 'https://dash.coinpler.com/api/endpoint.php';
        localStorage.AppId = '59';
        localStorage.store_id = '59';
    }, []);

    // ✅ Function registry system
    const registerFunction = (name: string, fn: (...args: any[]) => any) => {
        functionRegistry.current[name] = fn;
    };

    const callFunction = (name: string, ...args: any[]) => {
        const fn = functionRegistry.current[name];
        if (fn) {
            return fn(...args);
        } else {
            console.warn(`Function "${name}" is not registered.`);
        }
    };

    const showToast = (message: string, duration: number = 3000) => {
        setToastMessage(message);
        setToastVisible(true);
        setTimeout(() => setToastVisible(false), duration);
    };

    return (
        <FunctionContext.Provider value={{ registerFunction, callFunction, showToast }}>
            <IonPage className="light-theme">
                <IonContent className="app_layout_content">
                    <div className="app_layout_shell">
                        {children}
                    </div>
                </IonContent>

                <IonToast 
                    isOpen={toastVisible} 
                    message={toastMessage} 
                    duration={null} 
                    onDidDismiss={() => setToastVisible(false)} 
                    buttons={[
                        {
                            text: '✖', // X button
                            role: 'cancel',
                            handler: () => setToastVisible(false),
                        },
                    ]}
                />
            </IonPage>
        </FunctionContext.Provider>
    );
};

// ✅ Custom Hook to Use Function Service
export const useFunctionService = () => {
    const context = useContext(FunctionContext);
    if (!context) {
        throw new Error('useFunctionService must be used within a Layout component');
    }
    return context;
};

export default Layout;
