import React, { createContext, useContext, useEffect, useState } from 'react';

import { clearToken, getToken } from '@/services/http';
import { getUserInfo, logout as logoutApi, UserInfo } from '@/services/user';

interface AuthContextType {
  isLoggedIn: boolean;
  user: UserInfo | null;
  loading: boolean;
  refreshUser: () => Promise<void>;
  logout: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType>({
  isLoggedIn: false,
  user: null,
  loading: true,
  refreshUser: async () => {},
  logout: async () => {},
});

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<UserInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [hasToken, setHasToken] = useState(false);

  const refreshUser = async () => {
    try {
      const token = getToken();
      setHasToken(!!token);
      if (token) {
        const info = await getUserInfo();
        setUser(info);
      } else {
        setUser(null);
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      setUser(null);
    }
  };

  const logout = async () => {
    try {
      await logoutApi();
    } catch (e) {
      console.warn('Logout API failed', e);
    }
    setUser(null);
    setHasToken(false);
    await clearToken();
  };

  useEffect(() => {
    const init = async () => {
      await refreshUser();
      setLoading(false);
    };
    init();
  }, []);

  return (
    <AuthContext.Provider
      value={{
        isLoggedIn: hasToken,
        user,
        loading,
        refreshUser,
        logout,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

export const useAuth = () => useContext(AuthContext);
