import { useState, useEffect, useCallback, useRef } from 'react';
import { supabase } from '../supabase/client';
import type { ProductionPlan, WashingPlan } from '../types';

export type DashboardRole = 'purchaser' | 'textile' | 'washing';

interface DashboardStats {
  all: number;
  producing: number;
  completed: number;
}

interface UseDashboardDataOptions {
  role: DashboardRole;
  companyId: string | null;
}

interface DashboardDataState<T> {
  plans: T[];
  stats: DashboardStats;
  loading: boolean;
  error: Error | null;
  rejectedPlanIds: Set<string>;
}

/**
 * 统一的 Dashboard 数据获取 Hook
 * 根据角色自动选择正确的数据源和过滤逻辑
 */
export function useDashboardData<T = ProductionPlan | WashingPlan>({
  role,
  companyId
}: UseDashboardDataOptions) {
  const [state, setState] = useState<DashboardDataState<T>>({
    plans: [],
    stats: { all: 0, producing: 0, completed: 0 },
    loading: true,
    error: null,
    rejectedPlanIds: new Set()
  });

  // 缓存引用，避免重复请求
  const cacheRef = useRef<{
    data: DashboardDataState<T> | null;
    timestamp: number;
  }>({ data: null, timestamp: 0 });

  const CACHE_DURATION = 5000; // 5秒缓存

  // 计算统计数据
  const calculateStats = useCallback((plans: T[], roleType: DashboardRole): DashboardStats => {
    const all = plans.length;
    let producing = 0;
    let completed = 0;

    if (roleType === 'washing') {
      // 水洗厂使用 processing 状态
      producing = (plans as WashingPlan[]).filter(p => p.status === 'processing').length;
      completed = (plans as WashingPlan[]).filter(p => p.status === 'completed').length;
    } else {
      // 采购商和纺织厂使用 producing 状态
      producing = (plans as ProductionPlan[]).filter(p => p.status === 'producing').length;
      completed = (plans as ProductionPlan[]).filter(p => p.status === 'completed').length;
    }

    return { all, producing, completed };
  }, []);

  // 获取采购商数据
  const fetchPurchaserData = useCallback(async () => {
    if (!companyId) return;

    const { data: planData, error } = await supabase
      .from('production_plans')
      .select('*')
      .eq('purchaser_id', companyId)
      .order('created_at', { ascending: false });

    if (error) throw error;

    // 获取流程步骤，检测 rejected 状态
    const planIds = (planData || []).map(p => p.id);
    const { data: stepsData } = await supabase
      .from('plan_process_steps')
      .select('plan_id, status')
      .in('plan_id', planIds);

    const rejectedIds = new Set<string>();
    (stepsData || []).forEach(step => {
      if (step.status === 'rejected') {
        rejectedIds.add(step.plan_id);
      }
    });

    const filteredPlans = (planData || []).filter(p => !rejectedIds.has(p.id)) as T[];
    const stats = calculateStats(filteredPlans, 'purchaser');

    return { plans: filteredPlans, stats, rejectedPlanIds: rejectedIds };
  }, [companyId, calculateStats]);

  // 获取纺织厂数据
  const fetchTextileData = useCallback(async () => {
    if (!companyId) return;

    // 先获取关联的计划ID
    const { data: planFactories } = await supabase
      .from('plan_factories')
      .select('plan_id')
      .eq('factory_id', companyId)
      .eq('factory_type', 'textile');

    if (!planFactories || planFactories.length === 0) {
      return { plans: [] as T[], stats: { all: 0, producing: 0, completed: 0 }, rejectedPlanIds: new Set<string>() };
    }

    const planIds = planFactories.map(pf => pf.plan_id);
    const { data: planData, error } = await supabase
      .from('production_plans')
      .select('*')
      .in('id', planIds)
      .order('created_at', { ascending: false });

    if (error) throw error;

    // 获取流程步骤，检测 rejected 状态
    const { data: stepsData } = await supabase
      .from('plan_process_steps')
      .select('plan_id, status')
      .in('plan_id', planIds);

    const rejectedIds = new Set<string>();
    (stepsData || []).forEach(step => {
      if (step.status === 'rejected') {
        rejectedIds.add(step.plan_id);
      }
    });

    const filteredPlans = (planData || []).filter(p => !rejectedIds.has(p.id)) as T[];
    const stats = calculateStats(filteredPlans, 'textile');

    return { plans: filteredPlans, stats, rejectedPlanIds: rejectedIds };
  }, [companyId, calculateStats]);

  // 获取水洗厂数据
  const fetchWashingData = useCallback(async () => {
    if (!companyId) return;

    const { data: washingPlans, error } = await supabase
      .from('washing_plans')
      .select('*')
      .eq('washing_factory_id', companyId)
      .order('created_at', { ascending: false });

    if (error) throw error;

    const plans = (washingPlans || []) as T[];
    const stats = calculateStats(plans, 'washing');

    return { plans, stats, rejectedPlanIds: new Set<string>() };
  }, [companyId, calculateStats]);

  // 主数据获取函数
  const fetchData = useCallback(async () => {
    if (!companyId) {
      setState(prev => ({ ...prev, loading: false }));
      return;
    }

    // 检查缓存
    const now = Date.now();
    if (cacheRef.current.data && (now - cacheRef.current.timestamp) < CACHE_DURATION) {
      setState(cacheRef.current.data);
      return;
    }

    try {
      let result: DashboardDataState<T> | undefined;

      switch (role) {
        case 'purchaser':
          result = await fetchPurchaserData() as DashboardDataState<T> | undefined;
          break;
        case 'textile':
          result = await fetchTextileData() as DashboardDataState<T> | undefined;
          break;
        case 'washing':
          result = await fetchWashingData() as DashboardDataState<T> | undefined;
          break;
      }

      if (result) {
        const newState = {
          plans: result.plans,
          stats: result.stats,
          loading: false,
          error: null,
          rejectedPlanIds: result.rejectedPlanIds
        };
        setState(newState);
        cacheRef.current = { data: newState, timestamp: now };
      }
    } catch (err) {
      setState(prev => ({
        ...prev,
        loading: false,
        error: err instanceof Error ? err : new Error('Unknown error')
      }));
    }
  }, [companyId, role, fetchPurchaserData, fetchTextileData, fetchWashingData]);

  // 初始加载和 companyId 变化时重新获取
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // 提供手动刷新方法
  const refresh = useCallback(() => {
    cacheRef.current = { data: null, timestamp: 0 };
    fetchData();
  }, [fetchData]);

  return {
    ...state,
    refresh
  };
}
