import { createContext, useContext, useState, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';

type AuthContextType = {
  isAuthenticated: boolean;
  domain: string | null;
  username: string | null;
  authData: any | null;
  setAuthState: (domain: string, username: string, authData: any) => Promise<void>;
  clearAuth: () => Promise<void>;
};

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [domain, setDomain] = useState<string | null>(null);
  const [username, setUsername] = useState<string | null>(null);
  const [authData, setAuthData] = useState<any | null>(null);

  // Load stored auth state on app start
  useEffect(() => {
    loadStoredAuth();
  }, []);

  const loadStoredAuth = async () => {
    try {
      const [storedDomain, storedUsername, storedAuthData] = await Promise.all([
        AsyncStorage.getItem('domain'),
        AsyncStorage.getItem('username'),
        AsyncStorage.getItem('authData')
      ]);
      
      if (storedDomain && storedUsername && storedAuthData) {
        setDomain(storedDomain);
        setUsername(storedUsername);
        setAuthData(JSON.parse(storedAuthData));
        setIsAuthenticated(true);
      }
    } catch (error) {
      console.error('Error loading auth state:', error);
    }
  };

  const setAuthState = async (newDomain: string, newUsername: string, newAuthData: any) => {
    try {
      await Promise.all([
        AsyncStorage.setItem('domain', newDomain),
        AsyncStorage.setItem('username', newUsername),
        AsyncStorage.setItem('authData', JSON.stringify(newAuthData))
      ]);
      
      setDomain(newDomain);
      setUsername(newUsername);
      setAuthData(newAuthData);
      setIsAuthenticated(true);
    } catch (error) {
      console.error('Error saving auth state:', error);
    }
  };

  const clearAuth = async () => {
    try {
      await Promise.all([
        AsyncStorage.removeItem('domain'),
        AsyncStorage.removeItem('authData')
      ]);
      
      setDomain(null);
      setUsername(null);
      setAuthData(null);
      setIsAuthenticated(false);
    } catch (error) {
      console.error('Error clearing auth state:', error);
    }
  };

  return (
    <AuthContext.Provider value={{ 
      isAuthenticated, 
      domain, 
      username,
      authData, 
      setAuthState, 
      clearAuth 
    }}>
      {children}
    </AuthContext.Provider>
  );
}

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}; 