'use client';

import React, { createContext, useContext, useState, ReactNode } from 'react';
import { getCurrentUserInfoApiV1AuthMeGet } from '@/lib/api/sdk.gen';

// Cookie 操作工具
const setTokenCookie = (token: string) => {
  if (typeof document !== 'undefined') {
    document.cookie = `auth-token=${token}; path=/; max-age=${7 * 24 * 60 * 60}`;
    console.log('🍪 Token已设置到cookie');
  }
};

const removeTokenCookie = () => {
  if (typeof document !== 'undefined') {
    document.cookie = 'auth-token=; path=/; max-age=0';
    console.log('🗑️ Token已从cookie中清除');
  }
};

interface User {
  id: string;
  username: string;
  realName: string;
  email?: string;
  phone?: string;
  enterpriseId?: string;
  token?: string;
}

interface AuthContextType {
  user: User | null;
  login: (user: User) => void;
  logout: () => void;
  isAuthenticated: boolean;
  loading: boolean;
  validateUser: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

interface AuthProviderProps {
  children: ReactNode;
}

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

  const login = (userData: User) => {
    setUser(userData);
    // 存储到 localStorage
    localStorage.setItem('user', JSON.stringify(userData));

    // 同时设置 cookie（供中间件使用）
    if (userData.token) {
      setTokenCookie(userData.token);
    }

    setLoading(false);
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem('user');
    removeTokenCookie(); // 清除 cookie
    setLoading(false);

    // 跳转到登录页
    if (typeof window !== 'undefined') {
      window.location.href = '/login';
    }
  };

  // 验证当前用户信息
  const validateUser = async () => {
    try {
      const storedUser = localStorage.getItem('user');
      if (!storedUser) {
        setLoading(false);
        return;
      }

      const userData = JSON.parse(storedUser);

      // 使用 SDK 调用 /api/v1/auth/me 验证用户信息
      const response = await getCurrentUserInfoApiV1AuthMeGet({
        headers: {
          'Authorization': `Bearer ${userData.token}`,
        },
      });

      if (response.data) {
        // 更新用户信息（可能包含最新的权限、角色等）
        setUser({
          ...userData,
          ...response.data, // 合并最新的用户信息
        });
        console.log('✅ 用户验证成功，最新用户信息:', response.data);
      } else {
        // Token无效，清除用户信息
        console.warn('⚠️ Token验证失败，清除用户信息');
        localStorage.removeItem('user');
        setUser(null);
      }
    } catch (error: any) {
      console.error('❌ 用户验证失败:', error);
      // 验证失败时也清除用户信息，避免不一致状态
      localStorage.removeItem('user');
      setUser(null);
    } finally {
      setLoading(false);
    }
  };

  // 初始化时检查 localStorage并验证用户
  React.useEffect(() => {
    // 检查是否有存储的用户信息和 token，并设置 cookie
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      try {
        const userData = JSON.parse(storedUser);
        if (userData.token && !document.cookie.includes('auth-token')) {
          setTokenCookie(userData.token);
          console.log('🔄 初始化时设置cookie');
        }
      } catch (error) {
        console.error('解析存储用户信息失败:', error);
        localStorage.removeItem('user');
      }
    }

    validateUser();
  }, []);

  const value: AuthContextType = {
    user,
    login,
    logout,
    isAuthenticated: !!user,
    loading,
    validateUser, // 暴露验证方法供手动刷新使用
  };

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

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}