import 'dart:async';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';

import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_download_manager/flutter_download_manager.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:generp/screens/WebERPScreen.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import '../Utils/commonServices.dart';

const MAX_PROGRESS = 100;

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

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

  @override
  State<WebERPIOS> createState() => _WebERPIOSState();
}

class _WebERPIOSState extends State<WebERPIOS> {
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

  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();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
    pullToRefreshController =
        kIsWeb
            ? null
            : PullToRefreshController(
              settings: pullToRefreshSettings,
              onRefresh: () async {
                if (defaultTargetPlatform == Platform.isAndroid) {
                  webViewController?.reload();
                } else if (defaultTargetPlatform == Platform.isIOS) {
                  webViewController?.loadUrl(
                    urlRequest: URLRequest(
                      url: await webViewController?.getUrl(),
                    ),
                  );
                }
              },
            );
    print("WebURL:${widget.url}");
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.mobile:
        connection = 'Online';
        break;
      case ConnectivityResult.wifi:
        connection = 'Online';
        break;
      case ConnectivityResult.none:
      default:
        connection = 'Offline';
    }
    return connection == "Online"
        ? Platform.isAndroid
            ? WillPopScope(
              onWillPop: () => onBackPressed(context),
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(BuildContext context) {
    return Scaffold(
      appBar: appbar(context, "ERP"),
      body: Container(
        child: Column(
          children: <Widget>[
            Expanded(
              child: Stack(
                children: [
                  InAppWebView(
                    initialUrlRequest: URLRequest(
                      url: WebUri(widget.url.toString()),
                    ),
                    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
                      ),
                      ios: IOSInAppWebViewOptions(
                        allowsInlineMediaPlayback: true,
                        allowsLinkPreview: true,
                        allowsBackForwardNavigationGestures: true,
                      ),
                    ),

                    androidOnPermissionRequest: (
                      InAppWebViewController controller,
                      String origin,
                      List<String> resources,
                    ) async {
                      return PermissionRequestResponse(
                        resources: resources,
                        action: PermissionRequestResponseAction.GRANT,
                      );
                    },
                    initialSettings: InAppWebViewSettings(
                      javaScriptEnabled: true,
                      allowFileAccess: true,
                      allowContentAccess: true,
                      clearCache: true,
                      blockNetworkLoads: false,
                      networkAvailable: true,
                      useOnLoadResource: true,
                      thirdPartyCookiesEnabled: true,
                      supportZoom: false,
                      geolocationEnabled: true,
                      safeBrowsingEnabled: false,
                      saveFormData: true,
                      allowFileAccessFromFileURLs: true,
                      useWideViewPort: true,
                      databaseEnabled: true,
                      domStorageEnabled: true,
                      allowsBackForwardNavigationGestures: true,
                      allowUniversalAccessFromFileURLs: true,
                      allowsLinkPreview: true,
                    ),
                    onPermissionRequest: (controller, request) async {
                      return PermissionResponse(
                        resources: request.resources,
                        action: PermissionResponseAction.GRANT,
                      );
                    },
                    keepAlive: InAppWebViewKeepAlive(),
                    // initialData:
                    //     InAppWebViewInitialData(baseUrl: WebUri(widget.url),data: ),
                    onWebViewCreated: (controller) {
                      webViewController = controller;
                      _controller.complete(controller);
                    },
                    pullToRefreshController: pullToRefreshController,
                    shouldOverrideUrlLoading: (
                      controller,
                      navigationAction,
                    ) async {
                      var uri = navigationAction.request.url!;
                      print("urib scgefes");
                      print(uri);
                      print(uri.scheme);
                      if (uri.scheme == "tel") {
                        // Launch the phone dialer app with the specified phone number
                        if (await canLaunch(uri.toString())) {
                          await launch(uri.toString());
                          return NavigationActionPolicy.CANCEL;
                        }
                      } else if (uri.scheme == "mailto") {
                        if (await canLaunch(uri.toString())) {
                          await launch(uri.toString());
                          return NavigationActionPolicy.CANCEL;
                        }
                      } else if (uri.scheme == "whatsapp") {
                        // Launch WhatsApp with the specified chat or phone number
                        if (await canLaunch(uri.toString())) {
                          await launch(uri.toString());
                          return NavigationActionPolicy.CANCEL;
                        }
                      }
                      // // Check if the URL is trying to access the camera for image upload
                      // if (uri.scheme == 'camera' && uri.path.contains('/camera/')) {
                      //   // Handle camera image upload here
                      //   // You might want to display a custom UI for image selection or directly trigger the camera
                      //   // You can use platform-specific plugins like image_picker for this purpose
                      //   // Once the image is selected, you can pass it to the web view using JavaScript injection
                      //   if (await canLaunch(uri.toString())) {
                      //     await launch(uri.toString());
                      //     return NavigationActionPolicy.CANCEL;
                      //   }
                      // }
                      return NavigationActionPolicy.ALLOW;
                    },

                    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")
                        ],
                      ),
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
