import React, { createContext, useState, useContext, useEffect } from 'react';
import { auth } from '../utils/auth';

interface AuthContextType {
  isLoggedIn: boolean;
  login: (token: string) => Promise<void>;
  logout: () => Promise<void>;
}

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

export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [isLoading, setIsLoading] = useState(true); // 添加加载状态

  // 初始化时检查登录状态
  useEffect(() => {
    const checkLoginStatus = async () => {
      try {
        const isUserLoggedIn = await auth.isLoggedIn();
        console.log('检查登录状态:', isUserLoggedIn);
        setIsLoggedIn(isUserLoggedIn);
      } catch (error) {
        console.error('检查登录状态失败:', error);
      } finally {
        setIsLoading(false);
      }
    };
    checkLoginStatus();
  }, []);

  const login = async (token: string) => {
    try {
      await auth.setToken(token);
      setIsLoggedIn(true);
    } catch (error) { 
      console.error('登录失败:', error);
    }
  };

  const logout = async () => {
    try {
      await auth.removeToken();
      setIsLoggedIn(false);
    } catch (error) {
      console.error('登出失败:', error);
    }
  };

  if (isLoading) {
    return null; // 或者返回一个加载指示器
  }

  return (
    <AuthContext.Provider value={{ isLoggedIn, login, logout }}>
      {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;
};