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

import { getUserInfo } from '../api';

const AuthContext = createContext(null);

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const initAuth = async () => {
        const storedToken = localStorage.getItem('token');
        const storedUser = localStorage.getItem('user');
        
        if (storedToken) {
            try {
                // 1. 优先尝试从本地获取
                if (storedUser) {
                    try {
                        const parsedUser = JSON.parse(storedUser);
                        // 如果本地数据包含 ID，直接使用
                        if (parsedUser.id) {
                             setUser(parsedUser);
                        } else {
                             // 如果没有 ID，标记为需要刷新
                             throw new Error("Missing ID in stored user");
                        }
                    } catch (e) {
                         // 解析失败或数据不完整，继续从服务器获取
                    }
                }

                // 2. 总是尝试从服务器获取最新信息（或作为兜底）
                // 这样可以确保 ID 存在，且信息是最新的
                const res = await getUserInfo();
                if (res.data) {
                    setUser(res.data);
                    localStorage.setItem('user', JSON.stringify(res.data));
                }
            } catch (error) {
                console.error("Failed to fetch user info:", error);
                // 如果 token 失效，可能需要登出？
                // 暂时不强制登出，只清除无效的本地 user
                if (!user) localStorage.removeItem('user');
            }
        }
        setLoading(false);
    };

    initAuth();
  }, []);

  const login = (userData) => {
    setUser(userData);
    localStorage.setItem('user', JSON.stringify(userData));
    if (userData.token) {
        localStorage.setItem('token', userData.token);
    }
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem('user');
    localStorage.removeItem('token');
  };
  
  const updateUser = (data) => {
      const newUser = { ...user, ...data };
      setUser(newUser);
      localStorage.setItem('user', JSON.stringify(newUser));
  };

  return (
    <AuthContext.Provider value={{ user, login, logout, updateUser, loading }}>
      {children}
    </AuthContext.Provider>
  );
};

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