// frontend/context/AuthContext.js

import React, { createContext, useState, useEffect } from 'react';
import * as SecureStore from 'expo-secure-store';
import { Alert } from 'react-native';
import jwtDecode from 'jwt-decode';
import { api, eventEmitter } from '../services/api'; // Import the Axios instance and EventEmitter

export const AuthContext = createContext();

/**
 * AuthProvider Component
 * Provides authentication context to the application.
 */
export const AuthProvider = ({ children }) => {
  const [authToken, setAuthToken] = useState(null);
  const [user, setUser] = useState(null); // Manage user object
  const [loading, setLoading] = useState(true); // Loading state to manage asynchronous operations

  const SIGNIN_KEY = 'authToken'; // Consistent key

  /**
   * Function to handle user sign-in
   * @param {String} token - JWT token received from the backend
   */
  const signIn = async (token) => {
    try {
      if (token && token.split('.').length === 3) { // Basic JWT structure validation
        setAuthToken(token);
        await SecureStore.setItemAsync(SIGNIN_KEY, token);
        console.log('Token stored successfully:', token); // Debugging

        // Decode the token to extract user information
        const decoded = jwtDecode(token);
        console.log('Decoded Token:', decoded); // Verify decoded data

        // Adjust according to your token payload
        setUser({
          id: decoded.userId || decoded.id, // Adjust based on your token's structure
          name: decoded.name || null,
          email: decoded.email || null,
        });
      } else {
        throw new Error('Invalid JWT token');
      }
    } catch (error) {
      console.error('Error during sign-in:', error);
      Alert.alert('Authentication Error', error.message || 'Failed to authenticate.');
    }
  };

  /**
   * Function to handle user sign-out
   */
  const signOut = async () => {
    try {
      setAuthToken(null);
      setUser(null);
      await SecureStore.deleteItemAsync(SIGNIN_KEY);
      console.log('Token removed successfully.');

      // Optionally, navigate to the login screen or reset navigation stack
      // e.g., navigation.reset({ index: 0, routes: [{ name: 'Login' }] });
    } catch (error) {
      console.error('Error during sign-out:', error);
      Alert.alert('Error', 'Failed to log out.');
    }
  };

  /**
   * Function to load the token from SecureStore on app start
   */
  const loadToken = async () => {
    try {
      const token = await SecureStore.getItemAsync(SIGNIN_KEY);
      if (token && token.split('.').length === 3) { // Basic JWT structure validation
        setAuthToken(token);
        console.log('Token loaded from SecureStore:', token); // Debugging

        // Decode the token to extract user information
        const decoded = jwtDecode(token);
        console.log('Decoded Token:', decoded); // Verify decoded data

        setUser({
          id: decoded.userId || decoded.id,
          name: decoded.name || null,
          email: decoded.email || null,
        });
      } else if (token) {
        console.warn('Stored token is invalid. Clearing it.');
        await SecureStore.deleteItemAsync(SIGNIN_KEY);
      } else {
        console.log('No token found.');
      }
    } catch (e) {
      console.log('Failed to load token:', e);
      Alert.alert('Loading Error', 'Failed to load authentication token.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadToken();

    // Listen for logout events emitted by api.js
    const handleLogout = () => {
      signOut();
      // Optionally, navigate to the login screen if navigation is accessible here
      // e.g., navigation.reset({ index: 0, routes: [{ name: 'Login' }] });
    };

    eventEmitter.on('logout', handleLogout);

    // Clean up the listener on unmount
    return () => {
      eventEmitter.off('logout', handleLogout);
    };
  }, []);

  return (
    <AuthContext.Provider value={{ authToken, user, loading, signIn, signOut }}>
      {!loading && children}
    </AuthContext.Provider>
  );
};


 ERROR  TypeError: Cannot read property 'on' of undefined

This error is located at:
    in AuthProvider (created by App)
    in App (created by withDevTools(App))
    in withDevTools(App)
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent), js engine: hermes
 ERROR  TypeError: Cannot read property 'on' of undefined

This error is located at:
    in AuthProvider (created by App)
    in App (created by withDevTools(App))
    in withDevTools(App)
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent), js engine: hermes