import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/widgets/custom_app_bar.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../resouce/base_color.dart';
import '../../shared/router_gage.dart';
import '../../widgets/alert/data_alert_model.dart';
import '../../widgets/back_button.dart';

enum PaymentProcess {
  begin,
  processing,
  success,
  failure;

  String get title {
    switch (this) {
      case PaymentProcess.begin:
        return 'Bắt đầu thanh toán';
      case PaymentProcess.processing:
        return 'Đang xử lý thanh toán';
      case PaymentProcess.success:
        return 'Thanh toán thành công';
      case PaymentProcess.failure:
        return 'Thanh toán thất bại';
    }
  }

  String get content {
    switch (this) {
      case PaymentProcess.begin:
        return 'Vui lòng tiến hành thanh toán.';
      case PaymentProcess.processing:
        return 'Hệ thống đang xử lý giao dịch của bạn.';
      case PaymentProcess.success:
        return 'Giao dịch của bạn đã hoàn tất.';
      case PaymentProcess.failure:
        return 'Giao dịch thất bại. Vui lòng thử lại.';
    }
  }
}

class PaymentWebViewInput {
  final String url;
  final String orderId;
  final bool isContract;
  final bool showAlertBack;
  final Function(PaymentProcess result)? callback;

  PaymentWebViewInput({
    required this.url,
    required this.orderId,
    this.isContract = false,
    this.showAlertBack = true,
    this.callback,
  });
}

class PaymentWebViewScreen extends BaseScreen {
  const PaymentWebViewScreen({super.key});

  @override
  State<PaymentWebViewScreen> createState() => _PaymentWebViewScreenState();
}

class _PaymentWebViewScreenState extends BaseState<PaymentWebViewScreen> with BasicState {
  late final PaymentWebViewInput input;
  late final WebViewController _controller;
  bool _isLoading = true;

  final List<String> paymentSuccessUrls = [
    "https://localhost/paymentGatewayRequestSuccessful",
    "mypointapp://open?click_action_type=PAYMENT_SUCCESS",
    "https://localhost/paymentGatewayAutoDebitRequestSuccessful",
  ];
  final List<String> paymentFailedUrls = [
    "https://localhost/paymentGatewayRequestFailed",
    "mypointapp://open?click_action_type=PAYMENT_FAIL",
    "https://localhost/paymentGatewayAutoDebitRequestFailed",
  ];

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    if (args is! PaymentWebViewInput) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Get.back();
      });
      return;
    }
    input = args;
    _controller =
        WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setNavigationDelegate(
            NavigationDelegate(
              onPageStarted: (_) {
                setState(() {
                  _isLoading = true;
                });
              },
              onPageFinished: (_) {
                setState(() {
                  _isLoading = false;
                });
              },
              onNavigationRequest: _handleNavigation,
            ),
          )
          ..loadRequest(Uri.parse(input.url));
  }

  @override
  Widget createBody() {
    return Scaffold(
      appBar: CustomAppBar(
        title: "Thanh toán",
        leftButtons: [
          CustomBackButton(
            onPressed: () async {
              if (input.showAlertBack) {
                _onBackPressed();
                return;
              }
              Get.back();
            },
          ),
        ],
      ),
      body: Stack(
        children: [
          WebViewWidget(controller: _controller),
          if (_isLoading) const Center(child: CircularProgressIndicator()),
        ],
      ),
    );
  }

  NavigationDecision _handleNavigation(NavigationRequest request) {
    final url = request.url;
    debugPrint("➡️ Navigating: $url");
    if (paymentSuccessUrls.any((success) => url.startsWith(success))) {
      _onPaymentResult(PaymentProcess.success);
      return NavigationDecision.prevent;
    }
    if (paymentFailedUrls.any((fail) => url.startsWith(fail))) {
      _onPaymentResult(PaymentProcess.failure);
      return NavigationDecision.prevent;
    }
    // Mở app Zalo nếu redirect đến scheme của nó
    final uri = Uri.tryParse(url);
    final zaloSchemes = ["zalo", "zalopay", "zalopay.api.v2"];
    if (uri != null && zaloSchemes.contains(uri.scheme)) {
      launchUrl(uri, mode: LaunchMode.externalApplication);
      return NavigationDecision.prevent;
    }
    return NavigationDecision.navigate;
  }

  void _onPaymentResult(PaymentProcess result) {
    if (input.isContract) {
      _navigateToContractScreen();
    } else if (input.callback != null) {
      input.callback!(result);
      Get.back(); // hoặc điều hướng phù hợp
    } else {
      _backToRoot();
    }
  }

  void _backToRoot() {
    Get.until((route) => route.isFirst);
  }

  void _navigateToContractScreen() {
    Get.snackbar('Thông báo', 'Đi tới danh sách hợp đồng điện'); // placeholder
  }

  _onBackPressed() {
    final dataAlert = DataAlertModel(
      title: "Huỷ đơn hàng?",
      description: "Bạn có chắc muốn huỷ thanh toán đơn hàng này?",
      localHeaderImage: "assets/images/ic_pipi_03.png",
      buttons: [
        AlertButton(
          text: "Đồng ý",
          onPressed: () {
            Get.offNamed(transactionHistoryDetailScreen, arguments: {"orderId": input.orderId ?? "", "canBack": false});
          },
          bgColor: BaseColor.primary500,
          textColor: Colors.white,
        ),
        AlertButton(
          text: "Huỷ",
          onPressed: () => Navigator.pop(context, false),
          bgColor: Colors.white,
          textColor: BaseColor.second500,
        ),
      ],
    );
    showAlert(data: dataAlert);
  }
}
