import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
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 '../../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.';
    }
  }
}

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;
    
    // Web platform: mở URL trong tab mới và đóng màn hình ngay
    if (kIsWeb) {
      WidgetsBinding.instance.addPostFrameCallback((_) async {
        await _openUrlInBrowser();
        if (mounted) {
          Get.back();
        }
      });
      return;
    }
    
    // Mobile platform: khởi tạo WebView
    _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() {
    // 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...'),
            ],
          ),
        ),
      );
    }
    
    // Mobile platform: hiển thị WebView
    return Scaffold(
      appBar: CustomNavigationBar(
        title: "Thanh toán",
        leftButtons: [
          CustomBackButton(
            onPressed: () async {
              if (input.showAlertBack) {
                _onBackPressed();
                return;
              }
              Get.back();
            },
          ),
        ],
      ),
      body: Stack(
        children: [
          WebViewWidget(
            controller: _controller,
            gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{
              Factory<VerticalDragGestureRecognizer>(VerticalDragGestureRecognizer.new),
            },
          ),
          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) {
      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(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(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);
  }
}
