import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:keyboard/data/api/response/keyboard_home_info_response.dart';
import 'package:keyboard/data/repository/account_repository.dart';
import 'package:keyboard/data/repository/keyboard_repository.dart';
import 'package:keyboard/module/intimacy_analyse/enums/intimacy_analyse_tab.dart';
import 'package:keyboard/module/keyboard_manage/keyboard_manage_page.dart';
import 'package:keyboard/module/store/new_discount/new_discount_page.dart';
import 'package:keyboard/module/store/store_page.dart';
import 'package:keyboard/module/user_profile/user_profile_page.dart';

import '../../data/api/response/keyboard_love_index_response.dart';
import '../../data/bean/member_info.dart';
import '../../plugins/keyboard_android_platform.dart';
import '../../utils/default_keyboard_helper.dart';
import '../../utils/keyboard_tutorial_util.dart';
import '../intimacy_analyse/intimacy_analyse_page.dart';
import '../intimacy_scale/intimacy_scale_page.dart';
import '../keyboard_guide/keyboard_guide_page.dart';
import '../profile/profile_page.dart';

@injectable
class KeyBoardController extends BaseController {
  final tag = "KeyBoardController";

  final KeyboardRepository keyboardRepository;

  final AccountRepository accountRepository;

  KeyboardHomeInfoResponse? get homeInfo => keyboardRepository.homeInfo.value;

  MemberInfo? get memberInfo => accountRepository.memberStatusInfo.value;

  bool get isLogin => accountRepository.isLogin.value;

  Rxn<KeyboardLoveIndexResponse> get loveIndex =>
      keyboardRepository.homeLoveIndex;
  static const int countdownTime = 10 * 60 * 100;
  final RxInt timeLeft = countdownTime.obs;
  Timer? _timer;

  final RxBool isShowBanner = true.obs;

  /// 是否选择为了默认键盘
  RxBool get isDefaultKeyboard => DefaultKeyboardHelper.isDefaultKeyboard;

  // 各项指标数据

  KeyBoardController(this.keyboardRepository, this.accountRepository);

  @override
  void onInit() {
    super.onInit();

    // 初始判断一次
    _updateBannerState();

    // 实时监听登录状态变化
    ever(accountRepository.isLogin, (_) {
      _updateBannerState();
    });

    // 实时监听会员信息变化
    ever(accountRepository.memberStatusInfo, (_) {
      _updateBannerState();
    });
  }

  /// 根据当前登录状态 & 会员信息更新 banner显示逻辑
  void _updateBannerState() {
    if (isLogin && (memberInfo?.isMember == true)) {

      isShowBanner.value = false;
      _timer?.cancel(); // 停止倒计时
    } else {

      if (isShowBanner.value == false) {
        isShowBanner.value = true;
      }
      if (_timer == null || !_timer!.isActive) {
        startCountdown();
      }
    }
  }

  void clickVip() {
    StorePage.start();
  }

  void clickIntimacyAnalyze() {
    debugPrint("click intimacy analyze");
    IntimacyAnalysePage.start(tab: IntimacyAnalyseTab.intimacyAnalyseReport);
  }

  void clickScreenshotReply() {
    debugPrint("click screenshot reply");
    IntimacyAnalysePage.start(
      tab: IntimacyAnalyseTab.intimacyAnalyseScreenshotReply,
    );
  }

  void clickEasyReply() {
    KeyboardTutorialUtil.start();
    debugPrint("click easy reply");
  }

  void clickGoKeyboardManage() {
    KeyboardManagePage.start();
  }

  void clickCloseBanner() {
    isShowBanner.value = false;

    debugPrint("click close banner");
  }

  void clickAvatar(bool isUser) {
    debugPrint("click avatar");
    if (!isUser) {
      ProfilePage.start();
    } else {
      UserProfilePage.start();
    }
  }

  void clickBanner() {
    debugPrint("click banner");
    NewDiscountPage.start();
  }

  void clickLovePercentage() {
    IntimacyScalePage.start();
  }

  void startCountdown() {
    _timer = Timer.periodic(const Duration(milliseconds: 10), (timer) {
      if (timeLeft.value > 0) {
        timeLeft.value--;
      } else {
        isShowBanner.value = false;
        timer.cancel();
      }
    });
  }

  @override
  void onClose() {
    super.onClose();
    _timer?.cancel();
  }

  String get formattedTime {
    final totalMillis = timeLeft.value * 10;
    final duration = Duration(milliseconds: totalMillis);

    final minutes = duration.inMinutes.toString().padLeft(2, '0');
    final seconds = (duration.inSeconds % 60).toString().padLeft(2, '0');
    final milliseconds = ((duration.inMilliseconds % 1000) ~/ 10)
        .toString()
        .padLeft(2, '0');

    return "$minutes:$seconds:$milliseconds";
  }
}
