import { useEffect, useRef, useCallback } from 'react';
import { supabase } from '../supabase/client';

// 订阅配置类型
interface SubscriptionConfig {
  table: string;
  event?: '*' | 'INSERT' | 'UPDATE' | 'DELETE';
  filter?: string;
}

// 回调函数类型
type ChangeCallback = () => void;

// 全局订阅管理器（单例模式）
class RealtimeSubscriptionManager {
  private static instance: RealtimeSubscriptionManager;
  private subscriptions: Map<string, { count: number; channel: any }> = new Map();
  private callbacks: Map<string, Set<ChangeCallback>> = new Map();

  static getInstance(): RealtimeSubscriptionManager {
    if (!RealtimeSubscriptionManager.instance) {
      RealtimeSubscriptionManager.instance = new RealtimeSubscriptionManager();
    }
    return RealtimeSubscriptionManager.instance;
  }

  // 生成订阅唯一键
  private getKey(config: SubscriptionConfig): string {
    return `${config.table}:${config.event || '*'}:${config.filter || 'all'}`;
  }

  // 订阅
  subscribe(config: SubscriptionConfig, callback: ChangeCallback): () => void {
    const key = this.getKey(config);

    // 添加回调
    if (!this.callbacks.has(key)) {
      this.callbacks.set(key, new Set());
    }
    this.callbacks.get(key)!.add(callback);

    // 如果该订阅已存在，增加引用计数
    if (this.subscriptions.has(key)) {
      const sub = this.subscriptions.get(key)!;
      sub.count++;
      return () => this.unsubscribe(key, callback);
    }

    // 创建新订阅
    const channel = supabase
      .channel(`realtime_${key}`)
      .on(
        'postgres_changes',
        {
          event: config.event || '*',
          schema: 'public',
          table: config.table,
          filter: config.filter
        },
        () => {
          // 触发所有回调
          this.callbacks.get(key)?.forEach(cb => cb());
        }
      )
      .subscribe();

    this.subscriptions.set(key, { count: 1, channel });

    // 返回取消订阅函数
    return () => this.unsubscribe(key, callback);
  }

  // 取消订阅
  private unsubscribe(key: string, callback: ChangeCallback): void {
    // 移除回调
    this.callbacks.get(key)?.delete(callback);

    // 减少引用计数
    const sub = this.subscriptions.get(key);
    if (sub) {
      sub.count--;

      // 如果没有引用，取消订阅
      if (sub.count <= 0) {
        sub.channel.unsubscribe();
        this.subscriptions.delete(key);
        this.callbacks.delete(key);
      }
    }
  }
}

// 全局实例
const subscriptionManager = RealtimeSubscriptionManager.getInstance();

/**
 * 统一的实时订阅 Hook
 * 自动管理订阅生命周期，避免重复订阅
 * @param config 订阅配置
 * @param callback 数据变化回调
 * @param enabled 是否启用订阅（默认 true）
 */
export function useRealtime(
  config: SubscriptionConfig,
  callback: ChangeCallback,
  enabled: boolean = true
): void {
  const callbackRef = useRef(callback);

  // 保持回调引用最新
  useEffect(() => {
    callbackRef.current = callback;
  }, [callback]);

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

    // 包装回调，确保使用最新引用
    const wrappedCallback = () => {
      callbackRef.current();
    };

    // 订阅
    const unsubscribe = subscriptionManager.subscribe(config, wrappedCallback);

    // 清理
    return () => {
      unsubscribe();
    };
  }, [config.table, config.event, config.filter, enabled]);
}

/**
 * 库存数据实时订阅 Hook
 * 合并 inventory_records 和 product_inventory_records 订阅
 */
export function useInventoryRealtime(
  companyId: string | null,
  onChange: ChangeCallback
): void {
  // 使用 ref 保持回调稳定
  const onChangeRef = useRef(onChange);
  useEffect(() => {
    onChangeRef.current = onChange;
  }, [onChange]);

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

    const wrappedCallback = () => onChangeRef.current();

    // 订阅 inventory_records 变化
    const unsub1 = subscriptionManager.subscribe(
      { table: 'inventory_records', event: '*' },
      wrappedCallback
    );

    // 订阅 product_inventory_records 变化
    const unsub2 = subscriptionManager.subscribe(
      { table: 'product_inventory_records', event: '*' },
      wrappedCallback
    );

    return () => {
      unsub1();
      unsub2();
    };
  }, [companyId]);
}

/**
 * 计划数据实时订阅 Hook
 */
export function usePlanRealtime(
  companyId: string | null,
  onChange: ChangeCallback
): void {
  const onChangeRef = useRef(onChange);
  useEffect(() => {
    onChangeRef.current = onChange;
  }, [onChange]);

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

    const wrappedCallback = () => onChangeRef.current();

    // 订阅 inventory_records 变化（影响计划完成进度）
    const unsub = subscriptionManager.subscribe(
      { table: 'inventory_records', event: '*' },
      wrappedCallback
    );

    return () => {
      unsub();
    };
  }, [companyId]);
}

/**
 * 手动触发刷新（用于需要主动刷新的场景）
 */
export function triggerRealtimeRefresh(table: string): void {
  // 触发该表的所有订阅回调
  const manager = RealtimeSubscriptionManager.getInstance();
  // 遍历所有订阅，找到匹配的表
  manager['subscriptions'].forEach((_, key) => {
    if (key.startsWith(`${table}:`)) {
      manager['callbacks'].get(key)?.forEach(cb => cb());
    }
  });
}
