import React, { useState, createContext, useContext } from 'react';

import {
  useQuery,
  useQueryClient,
} from '@tanstack/react-query';
import axios from 'axios';
import { tenantClientManager } from '../api/tenantClient';

// 租户超级管理员用户类型
type TenantSuperAdmin = {
  userId: number;
  username: string;
  message: string;
};

type User = TenantSuperAdmin;

// 认证上下文类型
interface AuthContextType<T = User> {
  user: T | null;
  token: string | null;
  login: (username: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  isAuthenticated: boolean;
  isLoading: boolean;
}

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

// 租户认证提供器组件 - 专门用于租户超级管理员认证
export const TenantAuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [token, setToken] = useState<string | null>(localStorage.getItem('tenant-token'));
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  const queryClient = useQueryClient();

  // 声明handleLogout函数
  const handleLogout = async () => {
    try {
      // 租户超级管理员登出不需要调用API，直接清除本地状态
    } catch (error) {
      console.error('登出请求失败:', error);
    } finally {
      // 清除本地状态
      setToken(null);
      setUser(null);
      setIsAuthenticated(false);
      localStorage.removeItem('tenant-token');
      // 清除Authorization头
      delete axios.defaults.headers.common['Authorization'];
      console.log('登出时已删除全局Authorization头');
      // 清除所有查询缓存
      queryClient.clear();
    }
  };

  // 使用useQuery检查登录状态
  const { isLoading } = useQuery({
    queryKey: ['tenant-auth', 'status', token],
    queryFn: async () => {
      if (!token) {
        setIsAuthenticated(false);
        setUser(null);
        return null;
      }

      try {
        // 设置全局默认请求头
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

        // 租户超级管理员不需要验证用户信息，直接认为有效
        // 因为租户认证使用固定的超级管理员账号
        const currentUser: User = {
          userId: 1,
          username: 'superadmin',
          message: '租户超级管理员'
        };

        setUser(currentUser);
        setIsAuthenticated(true);
        return { isValid: true, user: currentUser };
      } catch (error) {
        return { isValid: false };
      }
    },
    enabled: !!token,
    refetchOnWindowFocus: false,
    retry: false
  });

  const handleLogin = async (username: string, password: string): Promise<void> => {
    try {
      // 使用租户认证RPC客户端登录
      const response = await tenantClientManager.get().login.$post({
        json: {
          username,
          password
        }
      });

      if (!response.ok) {
        const result = await response.json();
        throw new Error(result.message || '登录失败');
      }

      const result = await response.json();

      // 保存token和用户信息
      const { token: newToken, userId, username: responseUsername } = result;

      // 设置全局默认请求头
      axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`;

      // 保存状态
      setToken(newToken);
      setUser({
        userId,
        username: responseUsername,
        message: '租户超级管理员'
      });
      setIsAuthenticated(true);
      localStorage.setItem('tenant-token', newToken);

    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        token,
        login: handleLogin,
        logout: handleLogout,
        isAuthenticated,
        isLoading
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

// 使用上下文的钩子
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth必须在TenantAuthProvider内部使用');
  }
  return context;
};