import { createContext, ReactNode, useContext, useEffect, useState } from 'react';
import { fetchPlatformSession, platformLogin, platformLogout } from '../services/api';

interface PlatformAuth {
  isAuthenticated: boolean;
  isLoading: boolean;
  login: (accessKey: string) => Promise<void>;
  logout: () => Promise<void>;
}

const PlatformAuthContext = createContext<PlatformAuth | null>(null);

export function PlatformAuthProvider({ children }: { children: ReactNode }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    let mounted = true;

    const load = async () => {
      setIsLoading(true);
      const authenticated = await fetchPlatformSession();
      const clientUnlocked = typeof window !== 'undefined' && window.sessionStorage.getItem('galpao_imperial_platform_unlocked') === '1';
      if (mounted) {
        setIsAuthenticated(authenticated && clientUnlocked);
        setIsLoading(false);
      }
    };

    void load();

    return () => {
      mounted = false;
    };
  }, []);

  const login = async (accessKey: string) => {
    await platformLogin(accessKey);
    if (typeof window !== 'undefined') {
      window.sessionStorage.setItem('galpao_imperial_platform_unlocked', '1');
    }
    setIsAuthenticated(true);
  };

  const logout = async () => {
    await platformLogout();
    if (typeof window !== 'undefined') {
      window.sessionStorage.removeItem('galpao_imperial_platform_unlocked');
    }
    setIsAuthenticated(false);
  };

  return (
    <PlatformAuthContext.Provider value={{ isAuthenticated, isLoading, login, logout }}>
      {children}
    </PlatformAuthContext.Provider>
  );
}

export function usePlatformAuth() {
  const context = useContext(PlatformAuthContext);
  if (!context) {
    throw new Error('usePlatformAuth must be used within PlatformAuthProvider');
  }
  return context;
}
