import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_download_manager/flutter_download_manager.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:permission_handler/permission_handler.dart';

import 'WebERPScreen.dart';

// const MAX_PROGRESS = 100;

Future runErpScreenApp2() async {
  await FlutterDownloader.initialize(
    debug: true, // optional: set false to disable printing logs to console
  );
  await Permission.storage.request();
}

class WebWhizzdomScreen extends StatefulWidget {
  final String whizzdom_url;
  const WebWhizzdomScreen({super.key, required this.whizzdom_url});

  @override
  State<WebWhizzdomScreen> createState() => _WebWhizzdomScreenState();
}

class _WebWhizzdomScreenState extends State<WebWhizzdomScreen> {
  final Completer<InAppWebViewController> _controller =
      Completer<InAppWebViewController>();
  var empId = "";
  var sessionId = "";
  bool isLoading = true;
  InAppWebViewController? webViewController;
  PullToRefreshController? pullToRefreshController;
  PullToRefreshSettings pullToRefreshSettings = PullToRefreshSettings(
    color: AppColors.app_blue,
  );
  bool pullToRefreshEnabled = true;

  final GlobalKey webViewKey = GlobalKey();
  var dl = DownloadManager();
  @override
  void initState() {
    //  loadData();
    pullToRefreshController =
        kIsWeb
            ? null
            : PullToRefreshController(
              settings: pullToRefreshSettings,
              onRefresh: () async {
                if (defaultTargetPlatform == TargetPlatform.android) {
                  webViewController?.reload();
                } else if (defaultTargetPlatform == TargetPlatform.iOS) {
                  webViewController?.loadUrl(
                    urlRequest: URLRequest(
                      url: await webViewController?.getUrl(),
                    ),
                  );
                }
              },
            );
    // print("URL:${widget.url}");
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Platform.isAndroid
        ? WillPopScope(
          onWillPop: () => onBackPressed(context),
          child: SafeArea(top: false, bottom: true, child: _scaffold(context)),
        )
        : _scaffold(context);
  }

  Widget _scaffold(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: appbar(context, "Whizzdom"),
      body: Container(
        child: Column(
          children: <Widget>[
            Expanded(
              child: Stack(
                children: [
                  InAppWebView(
                    initialUrlRequest: URLRequest(
                      url: WebUri(widget.whizzdom_url),
                    ),
                    androidOnGeolocationPermissionsShowPrompt: (
                      InAppWebViewController controller,
                      String origin,
                    ) async {
                      return GeolocationPermissionShowPromptResponse(
                        origin: origin,
                        allow: true,
                        retain: true,
                      );
                    },
                    initialOptions: InAppWebViewGroupOptions(
                      android: AndroidInAppWebViewOptions(
                        useWideViewPort: true,
                        loadWithOverviewMode: true,
                        allowContentAccess: true,
                        geolocationEnabled: true,
                        allowFileAccess: true,
                        databaseEnabled: true, // Enables the WebView database
                        domStorageEnabled: true, // Enables DOM storage
                        builtInZoomControls:
                            true, // Enables the built-in zoom controls
                        displayZoomControls:
                            false, // Disables displaying zoom controls
                        safeBrowsingEnabled: true, // Enables Safe Browsing
                        clearSessionCache: true,
                      ),
                      ios: IOSInAppWebViewOptions(
                        allowsInlineMediaPlayback: true,
                      ),
                    ),

                    androidOnPermissionRequest: (
                      InAppWebViewController controller,
                      String origin,
                      List<String> resources,
                    ) async {
                      return PermissionRequestResponse(
                        resources: resources,
                        action: PermissionRequestResponseAction.GRANT,
                      );
                    },
                    onWebViewCreated: (controller) {
                      webViewController = controller;
                      _controller.complete(controller);
                    },
                    pullToRefreshController: pullToRefreshController,
                    onLoadStart: (controller, url) {
                      return setState(() {
                        isLoading = true;
                      });
                    },
                    onLoadStop: (controller, url) {
                      pullToRefreshController?.endRefreshing();
                      return setState(() {
                        isLoading = false;
                      });
                    },
                    onReceivedError: (controller, request, error) {
                      pullToRefreshController?.endRefreshing();
                    },
                    onProgressChanged: (controller, progress) {
                      if (progress == 100) {
                        pullToRefreshController?.endRefreshing();
                      }
                    },
                  ),
                  if (isLoading) ...[
                    Container(
                      color: Colors.white.withOpacity(0.7),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          SpinKitRing(
                            color: AppColors.app_blue,
                            lineWidth: 4,
                            // duration: Duration(seconds: 2),
                            size: 50,
                          ),
                          const SizedBox(height: 15),
                          SizedBox(
                            width: 200,
                            child: Text(
                              "Please wait.......",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                decorationThickness: 0,
                                fontSize: 15,
                                fontWeight: FontWeight.normal,
                                color: AppColors.app_blue,
                              ),
                            ),
                          ),

                          // SvgPicture.asset("/assets/images/NutsLoader.gif")
                        ],
                      ),
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
