import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { authAPI } from '../utils/api';
import toast from 'react-hot-toast';

const UserContext = createContext();

export const useUser = () => {
  const context = useContext(UserContext);
  if (!context) throw new Error('useUser must be used within a UserProvider');
  return context;
};

export const UserProvider = ({ children }) => {
  const [user, setUser] = useState(() => {
    try {
      const saved = localStorage.getItem('user');
      return saved ? JSON.parse(saved) : null;
    } catch { return null; }
  });
  const [isLoading, setIsLoading] = useState(true);
  const [isLoggedIn, setIsLoggedIn] = useState(() => localStorage.getItem('token') !== null);

  const clearSession = useCallback(() => {
    setUser(null);
    setIsLoggedIn(false);
    localStorage.removeItem('user');
    localStorage.removeItem('token');
    localStorage.removeItem('expiresAt');
  }, []);

  const fetchMe = useCallback(async () => {
    const token = localStorage.getItem('token');
    if (!token) { clearSession(); return false; }

    const expiresAt = localStorage.getItem('expiresAt');
    if (expiresAt && new Date(expiresAt) < new Date()) {
      clearSession();
      return false;
    }

    try {
      const res = await authAPI.me();
      const userData = res.data.user;
      setUser(userData);
      setIsLoggedIn(true);
      localStorage.setItem('user', JSON.stringify(userData));
      return true;
    } catch (err) {
      console.error('获取用户信息失败:', err);
      if (err.response?.status === 401 || err.response?.status === 403) {
        clearSession();
      }
      return false;
    }
  }, [clearSession]);

  const handleSSOCallback = useCallback((token, expiresAt, account, username) => {
    localStorage.setItem('token', token);
    if (expiresAt) localStorage.setItem('expiresAt', expiresAt);
    setUser({ account, username });
    setIsLoggedIn(true);
    localStorage.setItem('user', JSON.stringify({ account, username }));
    toast.success('登录成功！');
  }, []);

  const logout = useCallback(() => {
    clearSession();
    toast.success('已成功登出');
  }, [clearSession]);

  useEffect(() => {
    const init = async () => {
      setIsLoading(true);
      await fetchMe();
      setIsLoading(false);
    };
    init();
  }, [fetchMe]);

  const value = {
    user,
    isLoading,
    isLoggedIn,
    handleSSOCallback,
    fetchMe,
    logout,
    clearSession,
  };

  return (
    <UserContext.Provider value={value}>
      {children}
    </UserContext.Provider>
  );
};

export default UserContext;
