// ignore_for_file: library_private_types_in_public_api, deprecated_member_use

import 'package:didvan/constants/assets.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebView extends StatefulWidget {
  final String src;
  const WebView({Key? key, required this.src}) : super(key: key);

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

class _WebViewState extends State<WebView> {
  late WebViewController controller;
  bool loading = true;
  int progress = 0;

  final Set<Factory<VerticalDragGestureRecognizer>> gestureRecognizers = {
    Factory<VerticalDragGestureRecognizer>(
        () => VerticalDragGestureRecognizer())
  };

  void _onProgress(int progress) {
    setState(() {
      this.progress = progress;
    });
  }

  void _onPageFinished(String url) async {
    await Future.delayed(const Duration(seconds: 2));
    setState(() {
      if (progress == 100) loading = false;
    });
  }

  @override
  void initState() {
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: _onProgress,
          onPageStarted: (String url) {},
          onPageFinished: _onPageFinished,
          onHttpError: (HttpResponseError error) {},
          onWebResourceError: (WebResourceError error) {
            // navigatorKey.currentState!.pop();
          },
          onNavigationRequest: (NavigationRequest request) {
            // if (request.url.startsWith('https://www.youtube.com/')) {
            //   return NavigationDecision.prevent;
            // }
            return NavigationDecision.navigate;
          },
        ),
      )
      ..loadRequest(Uri.parse(widget.src));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          if (await controller.canGoBack()) {
            await controller.goBack();
            return false;
          } else {
            return true;
          }
        },
        child: Scaffold(
          appBar: AppBar(
            title: const DidvanText(
              'بازگشت به دیدوان',
            ),
            leading: const BackButton(),
          ),
          body: loading
              ? Center(
                  child: Image.asset(
                    Assets.loadingAnimation,
                    width: 60,
                    height: 60,
                  ),
                )
              : LayoutBuilder(builder: (context, constraints) {
                  return SizedBox(
                    width: MediaQuery.sizeOf(context).width,
                    height: MediaQuery.sizeOf(context).height,
                    child: WebViewWidget(
                      controller: controller,
                      gestureRecognizers: gestureRecognizers,
                    ),
                  );
                }),
        ));
  }
}
