import { useEffect, useRef, useCallback } from 'react';
import { supabase } from '../supabase/client';
import { SYNC_CONFIG } from '../config/app';
import { PLAN_STATUS, STEP_STATUS } from '../utils/constants';

interface PlanStatusCheckResult {
  planId: string;
  planCode: string;
  stepStatus: string;
  planStatus: string;
  needsFix: boolean;
}

/**
 * 检查计划状态是否一致
 * 如果 confirm 步骤已完成但计划状态仍为 pending，则需要修复
 */
export function usePlanStatusSync(companyId: string | undefined) {
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const isCheckingRef = useRef(false);

  const checkAndFixPlanStatus = useCallback(async () => {
    if (!companyId || isCheckingRef.current) return;
    
    isCheckingRef.current = true;
    
    try {
      // 获取当前纺织厂关联的所有计划
      const { data: planFactories } = await supabase
        .from('plan_factories')
        .select('plan_id')
        .eq('factory_id', companyId)
        .eq('factory_type', 'textile');

      if (!planFactories || planFactories.length === 0) {
        isCheckingRef.current = false;
        return;
      }

      const planIds = planFactories.map(pf => pf.plan_id);

      // 获取这些计划的流程步骤状态
      const { data: stepsData } = await supabase
        .from('plan_process_steps')
        .select('plan_id, step_type, status')
        .in('plan_id', planIds)
        .eq('step_type', 'confirm');

      // 获取计划当前状态
      const { data: plansData } = await supabase
        .from('production_plans')
        .select('id, plan_code, status')
        .in('id', planIds);

      if (!stepsData || !plansData) {
        isCheckingRef.current = false;
        return;
      }

      // 检查状态不一致的计划
      const inconsistentPlans: PlanStatusCheckResult[] = [];
      
      for (const plan of plansData) {
        const confirmStep = stepsData.find(s => s.plan_id === plan.id);
        
        // 如果 confirm 步骤已完成但计划状态仍为 pending，则需要修复
        if (confirmStep?.status === STEP_STATUS.COMPLETED && plan.status === PLAN_STATUS.PENDING) {
          inconsistentPlans.push({
            planId: plan.id,
            planCode: plan.plan_code,
            stepStatus: confirmStep.status,
            planStatus: plan.status,
            needsFix: true
          });
        }
      }

      // 自动修复状态不一致的计划
      if (inconsistentPlans.length > 0) {
        console.log(`[PlanStatusSync] 发现 ${inconsistentPlans.length} 个状态不一致的计划:`, inconsistentPlans);
        
        for (const item of inconsistentPlans) {
          const { error } = await supabase
            .from('production_plans')
            .update({ status: PLAN_STATUS.PRODUCING })
            .eq('id', item.planId);

          if (error) {
            console.error(`[PlanStatusSync] 修复计划 ${item.planCode} 失败:`, error);
          } else {
            console.log(`[PlanStatusSync] 已自动修复计划 ${item.planCode}: pending → producing`);
          }
        }
      }
    } catch (err) {
      console.error('[PlanStatusSync] 检查失败:', err);
    } finally {
      isCheckingRef.current = false;
    }
  }, [companyId]);

  useEffect(() => {
    if (!companyId) return;

    // 立即执行一次检查
    checkAndFixPlanStatus();

    // 同步间隔由配置中心管理（开发环境10秒，生产环境5分钟）
    intervalRef.current = setInterval(checkAndFixPlanStatus, SYNC_CONFIG.planStatusSyncInterval);

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    };
  }, [companyId, checkAndFixPlanStatus]);

  return { checkAndFixPlanStatus };
}
