import { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { getAuthConfig, login } from '../../lib/api';
import { getToken, setToken, clearToken } from '../../lib/auth';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [authMode, setAuthMode] = useState(null);
  const [keycloakConfig, setKeycloakConfig] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getAuthConfig()
      .then((config) => {
        setAuthMode(config.mode);
        setKeycloakConfig(config.keycloak);
        
        if (config.mode === 'simple') {
          const token = getToken();
          setIsAuthenticated(!!token);
        }
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const simpleLogin = useCallback(async (password) => {
    const result = await login(password);
    setToken(result.token);
    setIsAuthenticated(true);
    return result;
  }, []);

  const logout = useCallback(() => {
    clearToken();
    setIsAuthenticated(false);
  }, []);

  return (
    <AuthContext.Provider value={{
      isAuthenticated,
      authMode,
      keycloakConfig,
      loading,
      login: simpleLogin,
      logout,
    }}>
      {children}
    </AuthContext.Provider>
  );
}

// eslint-disable-next-line react-refresh/only-export-components
export function useAuth() {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within AuthProvider');
  }
  return context;
}
