import 'dart:async';

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:flutter_svg/svg.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/services/api_calling.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:math';

import 'package:flutter/widgets.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 WebErpScreen extends StatefulWidget {
  final String erp_url;
  const WebErpScreen({super.key,required this.erp_url});

  @override
  State<WebErpScreen> createState() => _WebErpScreenState();
}

class _WebErpScreenState extends State<WebErpScreen> {
  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 WillPopScope(
      onWillPop: () async {
        if (await webViewController!.canGoBack()) {
          webViewController!.goBack();
          return false; // Prevent default back button behavior
        }
        return true; // Allow default back button behavior
      },
      child: Scaffold(
        appBar: AppBar(

          elevation: 0,
          title: Container(
              child: Row(
                children: [

                  SizedBox(width: 10),
                  Container(
                    child: InkWell(
                      onTap: () => Navigator.pop(context, true),
                      child: Text("ERP",
                          textAlign: TextAlign.left,
                          style: TextStyle(
                            color: AppColors.semi_black,
                            fontSize: 18,
                          )),
                    ),
                  ),
                ],
              )),
          titleSpacing: 0,
          leading: Container(
            width: 10,
          ),
          leadingWidth: 20,
        ),
        body: Container(
            child: Column(children: <Widget>[
              Expanded(
                  child: Stack(
                    children: [
                      InAppWebView(
                        initialUrlRequest: URLRequest(
                          url: WebUri(widget.erp_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();
                          }
                        },
                        onConsoleMessage: (controller, consoleMessage) {
                          if (kDebugMode) {
                            debugPrint("consoleMessage${consoleMessage}");
                          }
                          debugPrint(
                              "JavaScript console message: ${consoleMessage.message}");
                        },
                        onDownloadStartRequest: (controller, url) async {
                          await ApiCalling.download_files(
                              empId, sessionId, "${url.url}", context)
                              .then((data) => {debugPrint(data)});

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


class SpinKitRing extends StatefulWidget {
  const SpinKitRing({
    Key? key,
    required this.color,
    this.lineWidth = 7.0,
    this.size = 50.0,
    this.duration = const Duration(milliseconds: 1200),
    this.controller,
  }) : super(key: key);

  final Color color;
  final double size;
  final double lineWidth;
  final Duration duration;
  final AnimationController? controller;

  @override
  State<SpinKitRing> createState() => _SpinKitRingState();
}

class _SpinKitRingState extends State<SpinKitRing> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation1;
  late Animation<double> _animation2;
  late Animation<double> _animation3;

  @override
  void initState() {
    super.initState();

    _controller = (widget.controller ?? AnimationController(vsync: this, duration: widget.duration))
      ..addListener(() {
        if (mounted) {
          setState(() {});
        }
      })
      ..repeat();
    _animation1 = Tween(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: const Interval(0.0, 1.0, curve: Curves.linear),
      ),
    );
    _animation2 = Tween(begin: -2 / 3, end: 1 / 2).animate(
      CurvedAnimation(
        parent: _controller,
        curve: const Interval(0.5, 1.0, curve: Curves.linear),
      ),
    );
    _animation3 = Tween(begin: 0.25, end: 5 / 6).animate(
      CurvedAnimation(
        parent: _controller,
        curve: const Interval(0.0, 1.0, curve: SpinKitRingCurve()),
      ),
    );
  }

  @override
  void dispose() {
    if (widget.controller == null) {
      _controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Transform(
        transform: Matrix4.identity()..rotateZ((_animation1.value) * 5 * pi / 6),
        alignment: FractionalOffset.center,
        child: SizedBox.fromSize(
          size: Size.square(widget.size),
          child: CustomPaint(
            foregroundPainter: RingPainter(
              paintWidth: widget.lineWidth,
              trackColor: widget.color,
              progressPercent: _animation3.value,
              startAngle: pi * _animation2.value,
            ),
          ),
        ),
      ),
    );
  }
}

class RingPainter extends CustomPainter {
  RingPainter({
    required this.paintWidth,
    this.progressPercent,
    this.startAngle,
    required this.trackColor,
  }) : trackPaint = Paint()
    ..color = trackColor
    ..style = PaintingStyle.stroke
    ..strokeWidth = paintWidth
    ..strokeCap = StrokeCap.square;

  final double paintWidth;
  final Paint trackPaint;
  final Color trackColor;
  final double? progressPercent;
  final double? startAngle;

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = (min(size.width, size.height) - paintWidth) / 2;
    canvas.drawArc(
      Rect.fromCircle(center: center, radius: radius),
      startAngle!,
      2 * pi * progressPercent!,
      false,
      trackPaint,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

class SpinKitRingCurve extends Curve {
  const SpinKitRingCurve();

  @override
  double transform(double t) => (t <= 0.5) ? 2 * t : 2 * (1 - t);
}
