import 'package:asciineverdie/src/core/engine/ad_service.dart';
import 'package:asciineverdie/src/core/engine/iap_service.dart';
import 'package:asciineverdie/src/core/engine/resurrection_service.dart';
import 'package:asciineverdie/src/core/engine/shop_service.dart';
import 'package:asciineverdie/src/core/model/game_state.dart';
import 'package:asciineverdie/src/core/model/monetization_state.dart';
import 'package:asciineverdie/src/core/storage/save_manager.dart';
import 'package:flutter/foundation.dart';

/// 부활 결과
class ResurrectionResult {
  const ResurrectionResult({
    required this.state,
    required this.monetization,
    required this.success,
  });

  final GameState state;
  final MonetizationState monetization;
  final bool success;
}

/// 사망 및 부활 처리를 담당하는 매니저
///
/// 일반 부활, 광고 부활, 자동 부활 등 모든 부활 관련 로직을 담당합니다.
class ResurrectionManager {
  ResurrectionManager();

  /// 자동 부활 활성화 여부
  bool autoResurrect = false;

  /// 자동 부활 조건 확인
  ///
  /// 다음 조건 중 하나라도 만족하면 자동 부활:
  /// 1. 수동 토글 자동부활 (autoResurrect)
  /// 2. 유료 유저 (IAP 광고 제거 구매)
  /// 3. 광고 부활 버프 활성 (10분간)
  bool shouldAutoResurrect({
    required MonetizationState monetization,
    required int elapsedMs,
  }) {
    return autoResurrect ||
        IAPService.instance.isAdRemovalPurchased ||
        monetization.isAutoReviveActive(elapsedMs);
  }

  /// 일반 부활 처리 (HP 50% 회복)
  ///
  /// Returns: 부활된 GameState (부활 불가 시 null)
  Future<GameState?> processResurrection({
    required GameState state,
    required SaveManager saveManager,
    required bool cheatsEnabled,
    required MonetizationState monetization,
  }) async {
    if (!state.isDead) return null;

    final shopService = ShopService(rng: state.rng);
    final resurrectionService = ResurrectionService(shopService: shopService);

    final resurrectedState = resurrectionService.processResurrection(state);

    // 저장
    await saveManager.saveState(
      resurrectedState,
      cheatsEnabled: cheatsEnabled,
      monetization: monetization,
    );

    debugPrint('[Resurrection] Normal resurrection complete');
    return resurrectedState;
  }

  /// 광고 부활 처리 (HP 100% + 아이템 복구 + 10분 자동부활 버프)
  ///
  /// 유료 유저: 광고 없이 부활
  /// 무료 유저: 리워드 광고 시청 후 부활
  ///
  /// Returns: ResurrectionResult (부활 불가/실패 시 success=false)
  Future<ResurrectionResult> processAdRevive({
    required GameState state,
    required SaveManager saveManager,
    required bool cheatsEnabled,
    required MonetizationState monetization,
  }) async {
    if (!state.isDead) {
      return ResurrectionResult(
        state: state,
        monetization: monetization,
        success: false,
      );
    }

    final shopService = ShopService(rng: state.rng);
    final resurrectionService = ResurrectionService(shopService: shopService);

    // 부활 처리 결과 저장용
    GameState? revivedState;
    MonetizationState updatedMonetization = monetization;

    void processRevive() {
      revivedState = resurrectionService.processAdRevive(state);

      // 10분 자동부활 버프 활성화 (elapsedMs 기준)
      final buffEndMs =
          revivedState!.skillSystem.elapsedMs + 600000; // 10분 = 600,000ms
      updatedMonetization = monetization.copyWith(autoReviveEndMs: buffEndMs);

      debugPrint(
        '[Resurrection] Ad revive complete, auto-revive buff until $buffEndMs ms',
      );
    }

    // 유료 유저는 광고 없이 부활
    if (IAPService.instance.isAdRemovalPurchased) {
      processRevive();
      await saveManager.saveState(
        revivedState!,
        cheatsEnabled: cheatsEnabled,
        monetization: updatedMonetization,
      );
      debugPrint('[Resurrection] Ad revive (paid user)');
      return ResurrectionResult(
        state: revivedState!,
        monetization: updatedMonetization,
        success: true,
      );
    }

    // 무료 유저는 리워드 광고 필요
    final adResult = await AdService.instance.showRewardedAd(
      adType: AdType.rewardRevive,
      onRewarded: processRevive,
    );

    if (adResult == AdResult.completed || adResult == AdResult.debugSkipped) {
      await saveManager.saveState(
        revivedState!,
        cheatsEnabled: cheatsEnabled,
        monetization: updatedMonetization,
      );
      debugPrint('[Resurrection] Ad revive (free user with ad)');
      return ResurrectionResult(
        state: revivedState!,
        monetization: updatedMonetization,
        success: true,
      );
    }

    debugPrint('[Resurrection] Ad revive failed: $adResult');
    return ResurrectionResult(
      state: state,
      monetization: monetization,
      success: false,
    );
  }
}
