import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.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 '../../directional/directional_screen.dart';
import '../../resources/base_color.dart';
import '../../shared/router_gage.dart';
import '../../widgets/alert/data_alert_model.dart';
import '../../widgets/back_button.dart';
import '../../widgets/custom_navigation_bar.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.';
    }
  }
}

/// Data required to kick off a payment session.
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();
}

/// Handles payment flows in an embedded WebView while listening for
/// provider callbacks and native schemes.
class _PaymentWebViewScreenState extends BaseState<PaymentWebViewScreen> with BasicState {
  late final PaymentWebViewInput input;
  WebViewController? _webViewController;
  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();
    if (!_hydrateArguments()) return;
    if (_handleWebPlatformLaunch()) return;
    _initializeMobileWebView();
  }

  bool _hydrateArguments() {
    final args = Get.arguments;
    if (args is PaymentWebViewInput) {
      input = args;
      return true;
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (Get.key.currentState?.canPop() ?? false) {
        Get.back();
      } else if (mounted) {
        Navigator.of(context).maybePop();
      }
    });
    return false;
  }

  bool _handleWebPlatformLaunch() {
    if (!kIsWeb) return false;
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await _openUrlInBrowser();
      if (mounted && Navigator.of(context).canPop()) {
        Navigator.of(context).pop();
      }
    });
    return true;
  }

  void _initializeMobileWebView() {
    _webViewController =
        WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..addJavaScriptChannel(
            'MyPoint',
            onMessageReceived: (JavaScriptMessage message) {
              final data = message.message;
              if (kDebugMode) {
                debugPrint('📩 JS Message: $data');
              }
              if (data.contains('payment_result')) {
                if (data.contains('success')) {
                  _onPaymentResult(PaymentProcess.success);
                } else if (data.contains('failure')) {
                  _onPaymentResult(PaymentProcess.failure);
                }
              }
            },
          )
          ..setNavigationDelegate(
            NavigationDelegate(
              onPageStarted: (_) => _setLoading(true),
              onPageFinished: (_) => _setLoading(false),
              onNavigationRequest: _handleNavigation,
              onWebResourceError: (error) {
                debugPrint('❌ WebView error: ${error.description}');
                _onPaymentResult(PaymentProcess.failure);
              },
            ),
          );
    _loadInitialPage();
  }

  @override
  Widget createBody() {
    // Web platform: hiển thị loading hoặc empty container
    if (kIsWeb) {
      return Scaffold(
        appBar: CustomNavigationBar(
          title: "Thanh toán",
          leftButtons: [
            CustomBackButton(onPressed: () => Get.back()),
          ],
        ),
        body: const Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 16),
              Text('Đang mở trang thanh toán...'),
            ],
          ),
        ),
      );
    }

    return Scaffold(
      appBar: CustomNavigationBar(
        title: "Thanh toán",
        leftButtons: [
          CustomBackButton(
            onPressed: () async {
              if (input.showAlertBack) {
                _onBackPressed();
                return;
              }
              Get.back();
            },
          ),
        ],
      ),
      body: Stack(
        children: [
          WebViewWidget(
            controller: _webViewController!,
            gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{
              Factory<VerticalDragGestureRecognizer>(VerticalDragGestureRecognizer.new),
            },
          ),
          if (_isLoading) const Center(child: CircularProgressIndicator()),
        ],
      ),
    );
  }

  void _loadInitialPage() {
    final formatted = formatUrl(input.url);
    final uri = Uri.tryParse(formatted);
    if (uri == null) {
      debugPrint('❌ Invalid payment URL: ${input.url}');
      _onPaymentResult(PaymentProcess.failure);
      return;
    }
    _webViewController?.loadRequest(uri);
  }

  void _setLoading(bool active) {
    if (_isLoading == active) return;
    if (!mounted) {
      _isLoading = active;
      return;
    }
    setState(() {
      _isLoading = active;
    });
  }

  String formatUrl(String rawUrl) {
    if (rawUrl.isEmpty) return rawUrl;
    if (rawUrl.startsWith('http://') || rawUrl.startsWith('https://')) {
      return rawUrl;
    }
    return 'https://$rawUrl';
  }

  NavigationDecision _handleNavigation(NavigationRequest request) {
    final url = request.url;
    if (kDebugMode) {
      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;
    }
    if (kDebugMode) {
      debugPrint("🔗 Handling URL scheme: ${uri?.scheme}");
    }
    // Xử lý chung mypointapp:// và các scheme ngoài http/https
    if (uri != null) {
      // mypointapp://open?click_action_type=PAYMENT_SUCCESS|PAYMENT_FAIL
      if (uri.scheme == 'mypointapp') {
        final action = uri.queryParameters['click_action_type'] ?? '';
        if (action == 'PAYMENT_SUCCESS') {
          _onPaymentResult(PaymentProcess.success);
          return NavigationDecision.prevent;
        }
        if (action == 'PAYMENT_FAIL') {
          _onPaymentResult(PaymentProcess.failure);
          return NavigationDecision.prevent;
        }
        final direction = DirectionalScreen.build(
          clickActionType: action,
          clickActionParam: uri.queryParameters['click_action_param'] ?? '',
        );
        final directionSuccess = direction?.begin();
        if (directionSuccess != true) {
          launchUrl(uri, mode: LaunchMode.externalApplication);
          return NavigationDecision.prevent;
        }
      }
      // Bất kỳ scheme không phải http/https: cố gắng mở ngoài
      if (uri.scheme.isNotEmpty && uri.scheme != 'http' && uri.scheme != 'https') {
        launchUrl(uri, mode: LaunchMode.externalApplication);
        return NavigationDecision.prevent;
      }
    }
    return NavigationDecision.navigate;
  }

  void _onPaymentResult(PaymentProcess result) {
    if (input.isContract) {
      _navigateToContractScreen();
    } else if (input.callback != null) {
      Get.back();
      input.callback!(result);
    } 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
  }

  /// Mở URL trong browser (web platform)
  Future<void> _openUrlInBrowser() async {
    try {
      final uri = Uri.parse(formatUrl(input.url));
      await launchUrl(
        uri,
        mode: LaunchMode.externalApplication,
      );
    } catch (e) {
      debugPrint('❌ Error opening URL: $e');
      // Fallback: mở trong tab hiện tại
      try {
        await launchUrl(
          Uri.parse(formatUrl(input.url)),
          mode: LaunchMode.platformDefault,
        );
      } catch (e2) {
        debugPrint('❌ Error opening URL (fallback): $e2');
      }
    }
  }

  void _onBackPressed() {
    final dataAlert = DataAlertModel(
      title: "Xác nhận huỷ thanh toán",
      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: "Tiếp tục thanh toán",
          onPressed: () => Navigator.pop(context, false),
          bgColor: BaseColor.primary500,
          textColor: Colors.white,
        ),
        AlertButton(
          text: "Dừng thanh toán",
          onPressed: () {
            Get.offNamed(
              transactionHistoryDetailScreen,
              arguments: {"orderId": input.orderId, "canBack": false},
            );
          },
          bgColor: Colors.white,
          textColor: BaseColor.second500,
        ),
      ],
    );
    showAlert(data: dataAlert);
  }
}
