import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:qpay/config/app_config.dart';
import 'package:qpay/screens/gateway/gateway_controller.dart';
import 'package:qpay/widgets/app_snack_bar.dart';
import 'package:webview_flutter/webview_flutter.dart';

class GatewayScreen extends StatefulWidget {
  const GatewayScreen({super.key});

  @override
  State<GatewayScreen> createState() => _GatewayScreenState();
}

class _GatewayScreenState extends State<GatewayScreen> {
  late WebViewController _webViewController;
  late GatewayController controller;
  late String url;
  String? sessionID;

  bool integrationStarted = false;

  @override
  void initState() {
    super.initState();
    controller = GatewayController(context);
    // https://na.gateway.mastercard.com/checkout/pay/SESSION0002220827459I8059951J88?checkoutVersion=1.0.0

    url = controller.transactionController.model.receiptData?['targetUrl'];

    _initWebView();
  }

  void _initWebView() async {
    _webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // Update loading bar.
          },
          onPageStarted: (String url) {
            controller.startLoading();
          },
          onPageFinished: (String url) {
            controller.finishLoading();
          },
          onHttpError: (HttpResponseError error) {},
          onWebResourceError: (WebResourceError error) {},
          onUrlChange: (UrlChange url) async {
            print("URL Changed to ${url.url!}");

            _navigateWhenDone(url.url!);
          },
        ),
      )
      ..loadRequest(Uri.parse(url));

    bool simulate = AppConfig.simulatePaymentSuccess;
    if (simulate) {
      await Future.delayed(Duration(seconds: 10));
      String targetUrl = url.replaceAll("/pay/", "/receipt/");
      _webViewController.loadRequest(Uri.parse(targetUrl));
    }
  }

  void _navigateWhenDone(String url) {
    if (url.contains("/checkout/receipt/")) {
      if (integrationStarted) {
        return;
      }

      AppSnackBar.show(
        context,
        'Payment was successful, please wait while we process your order.',
        backgroundColor: Colors.black87,
        duration: const Duration(seconds: 10),
      );

      setState(() {
        integrationStarted = true;
      });

      WidgetsBinding.instance.addPostFrameCallback((_) {
        context.go('/poll');
      });
    }
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Complete your payment'),
        leading: context.canPop()
            ? IconButton(
                onPressed: () {
                  context.pop();
                },
                icon: const Icon(Icons.arrow_back),
              )
            : SizedBox.shrink(),
      ),
      body: ListenableBuilder(
        listenable: controller,
        builder: (context, child) {
          if (controller.model.status == 'SUCCESS') {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              context.go('/integration');
            });
          }

          return controller.model.isLoading
              ? const Center(child: CircularProgressIndicator(strokeWidth: 5))
              : SizedBox.expand(
                  child: WebViewWidget(controller: _webViewController),
                );
        },
      ),
    );
  }
}
