/**
 * 后台同步管理器
 * 
 * 后台推送策略：
 * - 前台：WebSocket 实时通信
 * - 后台：断开 WebSocket，由 JPush 负责推送通知
 * - 回到前台：重连 WebSocket + 同步离线消息
 * 
 * 前台服务仅用于通话保活，不再用于消息同步。
 */

import { AppState, AppStateStatus, Platform } from 'react-native';
import { ForegroundServiceModule } from './ForegroundServiceModule';
import AsyncStorage from '@react-native-async-storage/async-storage';

/**
 * 后台同步模式
 */
export enum BackgroundSyncMode {
  /** 省电模式：仅依赖 JPush 推送 */
  BATTERY_SAVER = 'battery_saver',
  
  /** 实时模式：前台服务保活（仅用于通话） */
  REALTIME = 'realtime',
  
  /** 禁用后台同步 */
  DISABLED = 'disabled',
}

const STORAGE_KEY = 'background_sync_mode';

class BackgroundSyncManager {
  private mode: BackgroundSyncMode = BackgroundSyncMode.BATTERY_SAVER;
  private appStateSubscription: ReturnType<typeof AppState.addEventListener> | null = null;
  private isInitialized: boolean = false;
  private lastSyncAt: number = 0;
  private syncMessagesCallback: (() => Promise<void>) | null = null;

  /**
   * 设置消息同步回调函数
   * 由外部注入，避免循环依赖
   */
  setSyncMessagesCallback(callback: () => Promise<void>): void {
    this.syncMessagesCallback = callback;
  }

  /**
   * 初始化后台同步
   */
  async initialize(): Promise<void> {
    if (this.isInitialized) return;

    const savedMode = await this.loadMode();
    this.mode = savedMode;

    this.appStateSubscription = AppState.addEventListener(
      'change',
      this.handleAppStateChange
    );

    this.isInitialized = true;
    console.log('[BackgroundSyncManager] 初始化完成, 模式:', this.mode);
  }

  /**
   * 切换后台同步模式
   */
  async setMode(mode: BackgroundSyncMode): Promise<void> {
    if (AppState.currentState !== 'active' && this.mode === BackgroundSyncMode.REALTIME) {
      await ForegroundServiceModule.stop();
    }

    this.mode = mode;
    await this.saveMode(mode);

    if (mode === BackgroundSyncMode.REALTIME) {
      await ForegroundServiceModule.start({
        title: '威友',
        body: '正在后台运行',
      });
    } else {
      await ForegroundServiceModule.stop();
    }

    console.log('[BackgroundSyncManager] 模式已切换为:', mode);
  }

  /**
   * 获取当前模式
   */
  getMode(): BackgroundSyncMode {
    return this.mode;
  }

  /**
   * AppState 变化处理
   */
  private handleAppStateChange = async (nextState: AppStateStatus) => {
    console.log('[BackgroundSyncManager] AppState 变化:', nextState);

    if (nextState === 'active') {
      await this.onForeground();
    }
  };

  /**
   * 回到前台时的处理
   * 同步离线期间通过 JPush 推送的消息
   */
  private async onForeground(): Promise<void> {
    console.log('[BackgroundSyncManager] 回到前台，同步离线消息');
    await this.syncMessages();
  }

  /**
   * 执行消息同步
   */
  async syncMessages(): Promise<void> {
    const now = Date.now();
    if (now - this.lastSyncAt < 5000) {
      return;
    }
    this.lastSyncAt = now;

    if (this.syncMessagesCallback) {
      try {
        await this.syncMessagesCallback();
      } catch (error) {
        console.error('[BackgroundSyncManager] 同步失败:', error);
      }
    }
  }

  /**
   * 更新前台服务通知内容（仅通话场景使用）
   */
  async updateNotification(totalUnread: number): Promise<void> {
    if (this.mode !== BackgroundSyncMode.REALTIME) return;

    if (totalUnread > 0) {
      await ForegroundServiceModule.update(
        '威友',
        `您有 ${totalUnread} 条未读消息`
      );
    } else {
      await ForegroundServiceModule.update(
        '威友',
        '正在后台运行'
      );
    }
  }

  private async saveMode(mode: BackgroundSyncMode): Promise<void> {
    try {
      await AsyncStorage.setItem(STORAGE_KEY, mode);
    } catch (error) {
      console.error('[BackgroundSyncManager] 保存模式失败:', error);
    }
  }

  private async loadMode(): Promise<BackgroundSyncMode> {
    try {
      const saved = await AsyncStorage.getItem(STORAGE_KEY);
      return (saved as BackgroundSyncMode) || BackgroundSyncMode.BATTERY_SAVER;
    } catch (error) {
      return BackgroundSyncMode.BATTERY_SAVER;
    }
  }

  /**
   * 清理资源
   */
  async cleanup(): Promise<void> {
    this.appStateSubscription?.remove();
    this.appStateSubscription = null;
    await ForegroundServiceModule.stop();
    this.isInitialized = false;
  }
}

export const backgroundSyncManager = new BackgroundSyncManager();
