'use client'; // 标记为客户端组件，因为使用了useState, useEffect, useContext和localStorage

import React, { createContext, useState, useContext, useEffect, ReactNode, useCallback } from 'react';
import { useRouter } from 'next/navigation'; // 使用Next.js的路由
import { api } from '@/services/api';

// 用户类型定义 (与之前一致)
export interface User {
  id: number;
  username: string;
  role: string; // 确保这里的 'admin' 和后端 UserRoleEnum.ADMIN.getValue() 一致
  balance: number;
}

// 认证上下文类型
interface AuthContextType {
  user: User | null;
  isLoading: boolean;
  isAuthenticated: boolean;
  login: (username: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  register: (username: string, password: string, checkPassword: string) => Promise<void>;
  checkAuth: () => Promise<void>; // 新增：检查认证状态的函数
}

// 创建认证上下文
const AuthContext = createContext<AuthContextType | undefined>(undefined);

// 认证提供者属性
interface AuthProviderProps {
  children: ReactNode;
}

// 认证提供者组件
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true); // 初始为true，在checkAuth完成后设为false
  const router = useRouter();

  // 检查认证状态 (例如: 页面加载或需要权限时调用)
  const checkAuth = useCallback(async () => {
    console.log('Checking authentication status...');
    // 不需要在这里 setIsLoading(true)，因为初始值就是 true
    try {
      const response = await api.get('/user/current');
      if (response.data.code === 0 && response.data.data) {
        console.log('Data from /user/current for setUser:', JSON.stringify(response.data.data));
        setUser(response.data.data);
        console.log('User authenticated:', response.data.data.username, 'Role:', response.data.data.role);
      } else {
        setUser(null);
        console.log('User not authenticated or API error. Message:', response.data.message);
      }
    } catch (error: any) {
      console.error('Error checking auth:', error);
      setUser(null);
      // 如果 /user/current 返回 401/403，说明session无效或没有权限，这通常是预期行为，不需要特殊处理
    } finally {
      setIsLoading(false); // 无论成功与否，结束加载状态
      console.log('Auth check finished. isLoading set to false.');
    }
  }, []); // 移除了 router 依赖，因为它不直接使用 router

  // 组件挂载时执行一次认证检查
  useEffect(() => {
    checkAuth();
  }, [checkAuth]);

  // 登录函数
  const login = async (username: string, password: string) => {
    setIsLoading(true);
    try {
      const response = await api.post('/user/login', { username, password });
      if (response.data.code === 0 && response.data.data) {
        const loggedInUser = response.data.data as User;
        setUser(loggedInUser);
        console.log('Login successful for:', loggedInUser.username, 'Role:', loggedInUser.role);
        // 登录成功后跳转
        // 确保后端返回的 role 字符串与这里的判断条件一致 (e.g., 'admin')
        if (loggedInUser.role === 'admin') {
          router.push('/admin/dashboard');
        } else {
          router.push('/dashboard');
        }
      } else {
        throw new Error(response.data.message || '登录失败');
      }
    } catch (error: any) {
      console.error('登录出错:', error);
      setUser(null);
      throw error.message || error || '登录时发生未知错误';
    } finally {
      setIsLoading(false);
    }
  };

  // 注销函数
  const logout = async () => {
    // setIsLoading(true); // 可以考虑在登出操作期间也显示加载状态
    try {
      await api.post('/user/logout');
      console.log('Logout successful.');
    } catch (error: any) {
      console.error('注销API调用出错:', error);
    } finally {
      setUser(null);
      setIsLoading(false); 
      router.push('/login');
    }
  };

  // 注册函数
  const register = async (username: string, password: string, checkPassword: string) => {
    setIsLoading(true);
    try {
      const response = await api.post('/user/register', {
        username,
        password,
        checkPassword
      });
      if (response.data.code !== 0) {
        throw new Error(response.data.message || '注册失败');
      }
      console.log('Registration successful for:', username);
      // 注册成功后通常提示用户去登录，并跳转到登录页
      alert('注册成功！请登录。'); // 可以用更友好的提示组件替换 alert
      router.push('/login');
    } catch (error: any) {
      console.error('注册出错:', error);
      throw error.message || error || '注册时发生未知错误';
    } finally {
      setIsLoading(false);
    }
  };

  const value = {
    user,
    isLoading,
    isAuthenticated: !!user,
    login,
    logout,
    register,
    checkAuth // 提供检查函数
  };

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

// 自定义钩子便于使用上下文
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth必须在AuthProvider内部使用');
  }
  return context;
}; 