"use client";

import { createContext, useContext, useState, useEffect, ReactNode } from "react";
import api from "@/shared/api/axios";
import { ApiResponse, unwrap } from "@/shared/api/types";
import { User } from "@/shared/types/user";


interface AuthContextType {
  userId: string | null;
  user: User | null;
  isLoading: boolean;
  isAuthenticated: boolean;
  setUser: (user: User | null) => void;
}

const AuthContext = createContext<AuthContextType>({
  userId: null,
  user: null,
  isLoading: true,
  isAuthenticated: false,
  setUser: () => {},
});

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    let retryCount = 0;
    const maxRetries = 2;

    const fetchUser = async () => {
      console.log("[AuthContext] 开始获取用户信息...");
      try {
        const { data: res } = await api.get<ApiResponse<User>>('/api/auth/me');
        const payload = unwrap(res);
        console.log("[AuthContext] 获取用户信息成功:", payload);
        if (payload && payload.id) {
          setUser(payload);
          console.log("[AuthContext] 设置 user:", payload);
        } else {
          console.warn("[AuthContext] 响应中没有用户数据");
        }
        setIsLoading(false);
      } catch (error) {
        console.error("[AuthContext] 获取用户信息失败:", error);
        // 重试逻辑
        if (retryCount < maxRetries) {
          retryCount++;
          console.log(`[AuthContext] 重试 ${retryCount}/${maxRetries}...`);
          setTimeout(fetchUser, 1000);
        } else {
          console.error("[AuthContext] 重试次数用尽，放弃获取用户信息");
          setIsLoading(false);
        }
      }
    };

    fetchUser();
  }, []);

  return (
    <AuthContext.Provider value={{
      userId: user?.id || null,
      user,
      isLoading,
      isAuthenticated: !!user,
      setUser,
    }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
}
