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


import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:location/utils/common_expand.dart';

import '../../data/bean/member_status_info.dart';
import '../../resource/string.gen.dart';
import 'mine_countdown_timer_manager.dart'; // 导入全局定时器管理器

class MineTrialMembershipCountdownText extends StatefulWidget {
  final MemberStatusInfo? memberStatusInfo;
  final VoidCallback? trialHasExpiredCallBack;

  const MineTrialMembershipCountdownText({
    super.key,
    this.memberStatusInfo,
    this.trialHasExpiredCallBack,
  });

  @override
  State<MineTrialMembershipCountdownText> createState() => _MineTrialMembershipCountdownTextState();
}

class _MineTrialMembershipCountdownTextState extends State<MineTrialMembershipCountdownText> {
  final MineCountdownTimerManager _timerManager = MineCountdownTimerManager();
  String _countdownText = '';
  late String _countdownKey; // 倒计时唯一标识

  @override
  void initState() {
    super.initState();
    _countdownKey = 'member_trial_countdown_${widget.memberStatusInfo?.hashCode ?? ''}';
    _initCountdown();
  }

  @override
  void didUpdateWidget(covariant MineTrialMembershipCountdownText oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 检查memberStatusInfo是否有变化
    if (widget.memberStatusInfo != oldWidget.memberStatusInfo) {
      _countdownKey = 'member_trial_countdown_${widget.memberStatusInfo?.hashCode ?? ''}';
      _initCountdown();
    }
  }

  void _initCountdown() {
    if (widget.memberStatusInfo == null) {
      _countdownText = StringName.memberExperienceVip;
      return;
    }

    if (widget.memberStatusInfo?.trialed != true) {
      _countdownText = StringName.memberExperienceVip;
      _timerManager.cancelCountdown(_countdownKey);
      return;
    }

    final timestamp = widget.memberStatusInfo!.trialEndTimestamp ?? 0;
    if (timestamp == 0) {
      _countdownText = StringName.memberTrialHasExpired;
      _timerManager.cancelCountdown(_countdownKey);
      return;
    }

    // 启动全局倒计时
    _timerManager.startCountdown(
      key: _countdownKey,
      endTimestamp: timestamp,
      onExpired: () {
        if (mounted) {
          setState(() {
            _countdownText = StringName.memberTrialHasExpired;
          });
        }
      },
    );

    //widget.trialHasExpiredCallBack?.call();

    // 订阅倒计时更新
    _timerManager.getCountdownStream(_countdownKey).listen((formattedTime) {
      if (mounted) {
        setState(() {
          _countdownText = '${StringName.memberCountdownRemaining} $formattedTime ${StringName.memberCountdownExperienceTime}';
        });
      }
    });

    // 初始化时计算一次剩余时间
    _updateInitialTime();
  }

  void _updateInitialTime() {
    if (widget.memberStatusInfo == null || widget.memberStatusInfo?.trialed != true) {
      _countdownText = StringName.memberExperienceVip;
      return;
    }

    final timestamp = widget.memberStatusInfo!.trialEndTimestamp ?? 0;
    if (timestamp == 0) {
      _countdownText = StringName.memberTrialHasExpired;
      return;
    }

    DateTime endTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
    Duration remaining = endTime.difference(DateTime.now());

    if (remaining.inSeconds > 0) {
      String formattedTime = _timerManager.formatDuration(remaining);
      _countdownText = '${StringName.memberCountdownRemaining} $formattedTime ${StringName.memberCountdownExperienceTime}';
    } else {
      _countdownText = StringName.memberTrialHasExpired;
    }
  }

  @override
  void dispose() {
    //_timerManager.cancelCountdown(_countdownKey);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      _countdownText,
      style: TextStyle(
        fontSize: 13.sp,
        color: "#8A5F03".color,
        fontWeight: FontWeight.bold,
      ),
    );
  }
}
