
import 'dart:async';
import 'package:flutter/foundation.dart';

import '../../data/repositories/member_repository.dart';
import '../member/member_page.dart';
import 'mine_expiration_reminder_dialog.dart';

/// 全局倒计时定时器管理器（单例模式）
class MineCountdownTimerManager {
  static final MineCountdownTimerManager _instance = MineCountdownTimerManager._internal();
  factory MineCountdownTimerManager() => _instance;
  MineCountdownTimerManager._internal();

  // 存储所有倒计时任务
  final Map<String, Timer> _timers = {};
  final Map<String, StreamController<String>> _streamControllers = {};
  final Map<String, Completer<void>> _completers = {};

  var areShowAlartView = true;

  /// 启动倒计时
  Future<void> startCountdown({
    required String key, // 倒计时唯一标识
    required int endTimestamp, // 结束时间戳（毫秒）
    required VoidCallback onExpired, // 过期回调
  }) async {
    // 取消已存在的同名倒计时
    cancelCountdown(key);

    // 创建过期回调的Completer
    _completers[key] = Completer<void>();

    // 计算剩余时间
    DateTime endTime = DateTime.fromMillisecondsSinceEpoch(endTimestamp);
    Duration remaining = endTime.difference(DateTime.now());

    // 如果剩余时间小于等于0，直接触发过期回调
    if (remaining.inSeconds <= 0) {
      onExpired();
      return;
    }

    // 创建StreamController用于通知UI更新
    _streamControllers[key] = StreamController<String>.broadcast();

    // 创建定时器
    _timers[key] = Timer.periodic(Duration(seconds: 1), (timer) {
      DateTime currentTime = DateTime.now();
      Duration newRemaining = endTime.difference(currentTime);

      if (newRemaining.inSeconds <= 0) {
        // 倒计时结束
        timer.cancel();
        _timers.remove(key);
        _streamControllers[key]?.close();
        _streamControllers.remove(key);
        onExpired();
        _completers[key]?.complete();
        _completers.remove(key);

        if (areShowAlartView) {
          areShowAlartView = false;
          ///弹出提示框
          MemberRepository memberRepository = MemberRepository.getInstance();
          memberRepository
              .memberTrailInfo()
              .then((infoRespons) {
            MineExpirationReminderDialog.show(infoResponse: infoRespons,
                onDic: () {
                  areShowAlartView = true;
                  MemberPage.start(enterTyp: MemberPageType.afeterTrialMemberEnter);
                },
                cancelOnTap: () {
                  areShowAlartView = true;
                }
            );
            //MineExpirationReminderDialog.show(infoResponse: infoResponse);
          }).catchError((){
            areShowAlartView = true;
          });
        }

      } else {
        // 发送更新通知
        String formattedTime = formatDuration(newRemaining);
        _streamControllers[key]?.add(formattedTime);
      }
    });
  }

  /// 取消倒计时
  void cancelCountdown(String key) {
    _timers[key]?.cancel();
    _timers.remove(key);
    _streamControllers[key]?.close();
    _streamControllers.remove(key);
    _completers[key]?.complete();
    _completers.remove(key);
  }

  /// 格式化时间
  String formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    String hours = twoDigits(duration.inHours);
    String minutes = twoDigits(duration.inMinutes.remainder(60));
    String seconds = twoDigits(duration.inSeconds.remainder(60));
    print("hourssfsdfsd---${seconds}");
    return '$hours:$minutes:$seconds';
  }

  /// 获取倒计时流
  Stream<String> getCountdownStream(String key) {
    return _streamControllers[key]?.stream ?? Stream.empty();
  }

  /// 等待倒计时结束
  Future<void> waitForCountdown(String key) {
    return _completers[key]?.future ?? Future.value();
  }

  /// 清理所有倒计时
  void dispose() {
    _timers.forEach((key, timer) => timer.cancel());
    _timers.clear();
    _streamControllers.forEach((key, controller) => controller.close());
    _streamControllers.clear();
    _completers.clear();
  }
}