import React, { createContext, useState, useContext, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { loginService } from '../services/api';

// 用户游戏历史记录
export interface GameHistoryItem {
  gameType: string;
  roomId: string;
  roomCode: string;
  playedAt: Date;
  role: 'host' | 'player';
  result: any;
}

// 用户信息接口
export interface User {
  userId: string;
  nickName: string;
  avatarUrl: string;
  gender: number;
  gameHistory: GameHistoryItem[];
  premiumUser: boolean;
  createdAt: Date;
  lastLoginAt: Date;
}

// 用户上下文接口
interface UserContextData {
  user: User | null;
  token: string | null;
  isLoggedIn: boolean;
  isLoading: boolean;
  login: () => Promise<boolean>;
  logout: () => void;
  refreshUserInfo: () => Promise<boolean>;
}

// 创建上下文
const UserContext = createContext<UserContextData>({
  user: null,
  token: null,
  isLoggedIn: false,
  isLoading: true,
  login: async () => false,
  logout: () => {},
  refreshUserInfo: async () => false,
});

// 用户上下文提供者组件
export const UserProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [token, setToken] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // 初始化时从存储中获取用户信息
  useEffect(() => {
    const initUserFromStorage = async () => {
      try {
        const storedToken = Taro.getStorageSync('token');
        const storedUser = Taro.getStorageSync('user');

        if (storedToken && storedUser) {
          setToken(storedToken);
          setUser(JSON.parse(storedUser));
        }
      } catch (error) {
        console.error('从存储中获取用户信息失败:', error);
      } finally {
        setIsLoading(false);
      }
    };

    initUserFromStorage();
  }, []);

  // 登录方法
  const login = async (): Promise<boolean> => {
    setIsLoading(true);
    try {
      const res = await loginService.login();
      if (res.code === 200 && res.data) {
        const { token: newToken, user: userData } = res.data;
        setToken(newToken);
        setUser(userData);

        // 保存到本地存储
        Taro.setStorageSync('token', newToken);
        Taro.setStorageSync('user', JSON.stringify(userData));
        return true;
      }
      return false;
    } catch (error) {
      console.error('登录失败:', error);
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  // 登出方法
  const logout = () => {
    setToken(null);
    setUser(null);
    Taro.removeStorageSync('token');
    Taro.removeStorageSync('user');
  };

  // 刷新用户信息
  const refreshUserInfo = async (): Promise<boolean> => {
    if (!token) return false;

    setIsLoading(true);
    try {
      const res = await loginService.login();
      if (res.code === 200 && res.data) {
        const { user: userData } = res.data;
        setUser(userData);
        Taro.setStorageSync('user', JSON.stringify(userData));
        return true;
      }
      return false;
    } catch (error) {
      console.error('刷新用户信息失败:', error);
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  const value = {
    user,
    token,
    isLoggedIn: !!token && !!user,
    isLoading,
    login,
    logout,
    refreshUserInfo,
  };

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

// 自定义钩子，用于获取用户上下文
export const useUser = () => useContext(UserContext);

export default UserContext; 