import { useState, useCallback, useMemo, useEffect, useRef } from 'react';
import { getMyApprovalTasks } from '../service';
import type { DeployTeam } from '../types';

interface UsePendingApprovalOptions {
  teams: DeployTeam[];
  currentTeamId?: number | null;  // 当前选中的团队ID
  currentEnvId?: number | null;   // 当前选中的环境ID
  pollingEnabled?: boolean;
  pollingInterval?: number; // 轮询间隔，默认30秒
}

/**
 * 待审批数据管理 Hook
 * 负责管理待审批任务的加载和刷新
 * 优化：添加智能轮询，与部署数据同步刷新
 * 支持按团队和环境筛选待审批任务
 */
export function usePendingApproval({ 
  teams, 
  currentTeamId,
  currentEnvId,
  pollingEnabled = true,
  pollingInterval = 30000 // 默认30秒
}: UsePendingApprovalOptions) {
  const [approvalModalOpen, setApprovalModalOpen] = useState(false);
  const [pendingApprovalCount, setPendingApprovalCount] = useState(0);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  // 提取所有工作流定义键（去重）- 使用 useMemo 避免重复计算
  const workflowDefinitionKeys = useMemo(() => {
    const workflowKeys = teams.flatMap(team => 
      team.environments.flatMap(env => 
        env.applications
          .map(app => app.workflowDefinitionKey)
          .filter((key): key is string => !!key)
      )
    );
    return Array.from(new Set(workflowKeys));
  }, [teams]);

  // 加载待审批数量 - 使用 useCallback 避免重复创建
  const loadPendingApprovalCount = useCallback(async () => {
    if (!pollingEnabled || workflowDefinitionKeys.length === 0) {
      return;
    }
    
    try {
      // 传递 teamId 和 environmentId 参数精确筛选
      const response = await getMyApprovalTasks(
        workflowDefinitionKeys,
        currentTeamId || undefined,
        currentEnvId || undefined
      );
      if (response) {
        setPendingApprovalCount(response.length || 0);
      }
    } catch (error) {
      // 静默失败，不影响主页面
      console.error('Failed to load pending approval count:', error);
    }
  }, [workflowDefinitionKeys, currentTeamId, currentEnvId, pollingEnabled]);

  // 轮询待审批数量
  useEffect(() => {
    if (!pollingEnabled || workflowDefinitionKeys.length === 0) {
      return;
    }

    // 清除旧的定时器
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }

    // 立即加载一次
    loadPendingApprovalCount();

    // 设置定时轮询
    intervalRef.current = setInterval(loadPendingApprovalCount, pollingInterval);

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [loadPendingApprovalCount, pollingEnabled, workflowDefinitionKeys.length, pollingInterval]);

  return {
    approvalModalOpen,
    setApprovalModalOpen,
    pendingApprovalCount,
    workflowDefinitionKeys,
    loadPendingApprovalCount,
    refreshApprovalCount: loadPendingApprovalCount
  };
}
