/**
 * 团队相关钩子
 * 作者: 阿瑞
 * 功能: 提供团队状态管理的自定义钩子函数
 * 版本: 1.0.0
 */

'use client';

import React, { createContext, useContext, useState, useEffect, useMemo, useCallback } from 'react';
import { useParams } from 'next/navigation';
import { ITeamBasicInfo } from '@/models/system/types';
//import { DefaultRoleType } from '@/models/system/types/IUserRole';
import { useUserInfo } from './useUser';

// 动态导入TeamModel以避免客户端引入服务器端模块
//let TeamModel: any;

// 创建一个异步数据获取函数，用于从API获取团队数据
async function fetchTeamsByWorkspace(
  workspaceId: number, 
  userId: number | undefined, 
  //roleType: DefaultRoleType | undefined
): Promise<ITeamBasicInfo[]> {
  try {
    const response = await fetch(`/api/teams?workspaceId=${workspaceId}&userId=${userId || ''}`);
    if (!response.ok) throw new Error('获取团队列表失败');
    const data = await response.json();
    return data.success ? data.data : [];
  } catch (error) {
    console.error('获取团队列表失败:', error);
    return [];
  }
}

// 创建一个异步数据获取函数，用于从API获取团队信息
async function fetchTeamByCode(teamCode: string): Promise<ITeamBasicInfo | null> {
  try {
    const response = await fetch(`/api/teams/${teamCode}`);
    if (!response.ok) throw new Error('获取团队信息失败');
    const data = await response.json();
    return data.success ? data.data : null;
  } catch (error) {
    console.error('获取团队信息失败:', error);
    return null;
  }
}

/**
 * 团队上下文状态类型
 */
interface TeamContextState {
  currentTeam: ITeamBasicInfo | null;
  isLoading: boolean;
  error: string | null;
  teams: ITeamBasicInfo[];
  loadTeams: () => Promise<void>;
  setSelectedTeam: (team: ITeamBasicInfo) => void;
}

// 创建上下文
const TeamContext = createContext<TeamContextState | undefined>(undefined);

/**
 * 团队Provider组件
 */
export const TeamProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const params = useParams();
  const userInfo = useUserInfo();
  const [currentTeam, setCurrentTeam] = useState<ITeamBasicInfo | null>(null);
  const [teams, setTeams] = useState<ITeamBasicInfo[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  
  const teamCode = params?.teamCode as string;
  
  /**
   * 加载团队列表
   */
  const loadTeams = useCallback(async () => {
    try {
      // 确保用户已登录且有工作空间ID
      if (userInfo?.workspace?.id) {
        const workspaceId = userInfo.workspace.id;
        const userId = userInfo.id;
        
        // 使用fetch API从后端获取数据，而不是直接在客户端使用TeamModel
        const teamsData = await fetchTeamsByWorkspace(workspaceId, userId);
        setTeams(teamsData);
      }
    } catch (error) {
      console.error('加载团队列表失败:', error);
    }
  }, [userInfo?.workspace?.id, userInfo?.id]);
  
  /**
   * 加载指定代码的团队信息
   */
  const loadTeamByCode = useCallback(async (code: string) => {
    setIsLoading(true);
    setError(null);
    
    try {
      // 使用fetch API从后端获取数据，而不是直接在客户端使用TeamModel
      const team = await fetchTeamByCode(code);
      if (team) {
        setCurrentTeam(team);
      } else {
        setError('找不到指定的团队');
      }
    } catch (error) {
      console.error('加载团队信息失败:', error);
      setError('加载团队信息失败');
    } finally {
      setIsLoading(false);
    }
  }, []);
  
  /**
   * 设置当前选中的团队
   */
  const setSelectedTeam = useCallback((team: ITeamBasicInfo) => {
    setCurrentTeam(team);
  }, []);
  
  // 当团队代码变化时加载团队信息
  useEffect(() => {
    if (teamCode) {
      loadTeamByCode(teamCode);
    }
  }, [teamCode, loadTeamByCode]);
  
  // 当用户信息变化时加载团队列表
  useEffect(() => {
    if (userInfo?.id) {
      loadTeams();
    }
  }, [userInfo?.id, userInfo?.workspace?.id, loadTeams]);
  
  // 上下文值
  const value = useMemo(() => ({
    currentTeam,
    isLoading,
    error,
    teams,
    loadTeams,
    setSelectedTeam,
  }), [currentTeam, isLoading, error, teams, loadTeams, setSelectedTeam]);
  
  return (
    <TeamContext.Provider value={value}>
      {children}
    </TeamContext.Provider>
  );
};

/**
 * 使用团队钩子
 * @returns 团队上下文状态
 */
export const useTeam = (): TeamContextState => {
  const context = useContext(TeamContext);
  
  if (context === undefined) {
    throw new Error('useTeam必须在TeamProvider内部使用');
  }
  
  return context;
};

export default useTeam; 