import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../../app.dart';

class PaymentWebView extends StatefulWidget {
  final String url;
  PaymentWebView({Key? key, required this.url}) : super(key: key);

  @override
  State<PaymentWebView> createState() => _PaymentWebViewState();
}

class _PaymentWebViewState extends State<PaymentWebView> {
  bool _isLoading = true;
  final _key = UniqueKey();

  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) {
      WebView.platform = SurfaceAndroidWebView();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppbarWidget(leading: AppBarBackBtn()),
      body: Stack(
        children: [
          WebView(
            key: _key,
            javascriptMode: JavascriptMode.unrestricted,
            initialUrl: widget.url,
            onProgress: (int progress) {
              debugPrint('WebView is loading (progress : $progress%)');
            },
            onPageFinished: (finish) {
              setState(() {
                _isLoading = false;
              });
            },
            navigationDelegate: (NavigationRequest request) {
              setState(() {
                _isLoading = true;
              });
              if (request.url.startsWith(Constants.BASE_URL_WEB + 'checkout/success')) {
                debugPrint('if');
                CartController cc = Get.put(CartController());
                cc.clearCartAndNavigateToOrderList();

                return NavigationDecision.prevent;
              } else if (request.url.startsWith(Constants.BASE_URL_WEB + 'checkout/onepage')) {
                debugPrint('else if');
                Get.back();
                return NavigationDecision.prevent;
              }
              debugPrint('allowing navigation to $request');
              return NavigationDecision.navigate;
            },
          ),
          _isLoading
              ? Center(
                  child: CustomLoader(),
                )
              : Stack(),
        ],
      ),
    );
  }
}
