import 'package:domain/repository/payment_repository.dart';
import 'package:flutter/material.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_platform/engine/notify/notify_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/platform_export.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/util.dart';
import 'package:shared/utils/event_bus.dart';

part 'stripe_service.g.dart';

@Riverpod(keepAlive: true)
StripeService stripeService(Ref ref) {
  return StripeService(ref.read(paymentRepositoryProvider));
}

class StripeService {
  final PaymentRepository _paymentRepository;

  StripeService(this._paymentRepository); // 依赖注入 Dio 实例

  bool _isInitialized = false;

  // 4242 4242 4242 4242 – Visa （无需 3D）
  // 4000 0025 0000 3155 – 需要 3D Secure 验证

  //初始化 Stripe
  Future<void> _ensureInitialized() async {
    if (_isInitialized) return;

    Stripe.publishableKey = 'pk_test_51RMmxaRpg7SPAcNndAqMUMEOkRFsY5mL0JqJmdunL3vspxrYsGjGARQddaVu3ZQVEy1e1WTF8yalt0cYZCY8sK9R0005VIg5mC';
    await Stripe.instance.applySettings();

    Log.d("Stripe 初始化完成");
    _isInitialized = true;
  }

  ///执行支付
  Future<bool> executePayment({
    required String orderId,
  }) async {
    try {
      //尝试初始化 Stripe SDK
      await _ensureInitialized();

      //从服务端获取 clientSecret
      final clientSecret = await _fetchPaymentIntent(orderId);

      await _initializePaymentSheet(clientSecret);
      await Stripe.instance.presentPaymentSheet();

      Log.d("presentPaymentSheet 关闭，用户操作完成 !");

      return await _verifyPaymentResult(clientSecret);

    } on StripeException catch (e) {
      // Stripe SDK 出错
      _handleStripeError(e);
      return false;
    } catch (e) {
      // 其他的错误捕获
      _handleGenericError(e);
      return false;
    }
  }

  ///调用网络请求
  Future<String> _fetchPaymentIntent(String orderId) async {
    final result = await _paymentRepository.obtainPaymentIntent(orderId: orderId);
    if (result.isSuccess) {
      if (Utils.isNotEmpty(result.data?.clientSecret)) {
        return result.data!.clientSecret!;
      } else {
        throw Exception("Empty client secret");
      }
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
      throw Exception("Failed to get payment intent");
    }
  }

  Future<void> _initializePaymentSheet(String clientSecret) async {
    await Stripe.instance.initPaymentSheet(
      paymentSheetParameters: SetupPaymentSheetParameters(
        customFlow: false,
        paymentIntentClientSecret: clientSecret,
        merchantDisplayName: 'Your App Demo',
        style: ThemeMode.light,
        allowsDelayedPaymentMethods: false,
      ),
    );
  }

  Future<bool> _verifyPaymentResult(String clientSecret) async {
    final paymentIntent = await Stripe.instance.retrievePaymentIntent(clientSecret);

    switch (paymentIntent.status) {
      case PaymentIntentsStatus.Succeeded:
        NotifyEngine.showSuccess('支付成功');
        //发送 EventBus 事件
        bus.emit(AppConstant.eventStripePaymentSuccess, true);
        return true;
      case PaymentIntentsStatus.RequiresPaymentMethod:
        NotifyEngine.showFailure('支付方式无效');
        return false;
      case PaymentIntentsStatus.Processing:
        return await _handleProcessingPayment(clientSecret);
      default:
        return false;
    }
  }

  Future<bool> _handleProcessingPayment(String clientSecret) async {
    // 处理需要等待的支付状态
    await Future.delayed(const Duration(seconds: 2));
    final updatedIntent = await Stripe.instance.retrievePaymentIntent(clientSecret);

    return updatedIntent.status == PaymentIntentsStatus.Succeeded;
  }

  void _handleStripeError(StripeException e) {
    final errorMessage = e.error.localizedMessage ?? '支付失败';
    Log.e('Stripe Error: ${e.error.code} - $errorMessage');
    NotifyEngine.showError(errorMessage);
  }

  void _handleGenericError(dynamic e) {
    Log.e('System Error: $e');
    NotifyEngine.showError('支付异常:$e');
  }
}
