import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart';
import 'package:grocery_app/src/core/routes/routes.dart';
import 'package:grocery_app/utils/constants/assets_constant.dart';
import 'package:grocery_app/utils/extensions/extensions.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';

class PaymentWebView extends StatefulWidget {
  final String paymentUrl;

  PaymentWebView({required this.paymentUrl});

  @override
  _PaymentWebViewState createState() => _PaymentWebViewState();
}

class _PaymentWebViewState extends State<PaymentWebView> {
  InAppWebViewController? webViewController;
  bool _isLoading = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: Center(
          child: SizedBox(
            height: 20,
            width: 20,
            child: InkWell(
                onTap: () {
                  Navigator.of(context).pop();
                },
                child: SvgPicture.asset(
                  APPASSETS.back,
                  height: 20,
                  width: 20,
                )),
          ),
        ),
        title: const Text(
          "Complete Your Payment",
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.w700,
          ),
        ),
      ),
      body: Stack(
        children: [
          InAppWebView(
            initialUrlRequest:
                URLRequest(url: WebUri.uri(Uri.parse(widget.paymentUrl))),
            onWebViewCreated: (controller) {
              webViewController = controller;
            },
            onLoadStart: (controller, url) {
              setState(() {
                _isLoading = true; // Show loader when page starts loading
              });
            },
            onLoadStop: (controller, url) async {
              setState(() {
                _isLoading = false; // Hide loader when page finishes loading
              });
              if (url.toString().contains("success")) {
                context.clearAndPush(routePath: MyRoutes.SUCCESSPAYMENT);

                print("kjdsfkjghdfhgkjdfhgkjdf");
              } else if (url.toString().contains("failure")) {
                context.push(MyRoutes.PAYMENTFAILD);

                print("faild");
              }
            },
          ),
          // Loader Overlay
          if (_isLoading)
            Center(
              child: CircularProgressIndicator(
                color: Colors.green,
              ),
            ),
        ],
      ),
    );
  }
}
