// 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) {
    print('🌐 WebView loading progress: $progress%'); // Add logging
    setState(() {
      this.progress = progress;
    });
  }

  void _onPageFinished(String url) async {
    print('✅ WebView finished loading: $url'); // Add logging
    await Future.delayed(const Duration(seconds: 2));
    setState(() {
      if (progress == 100) loading = false;
    });
  }

  @override
  void initState() {
    print('🔄 Initializing WebView with URL: ${widget.src}'); // Add logging
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: _onProgress,
          onPageStarted: (String url) {
            print('▶️ WebView started loading: $url'); // Add logging
          },
          onPageFinished: _onPageFinished,
          onHttpError: (HttpResponseError error) {
            // print('❌ WebView HTTP error: ${error.statusCode} on ${error.url}'); // Add logging
          },
          onWebResourceError: (WebResourceError error) {
            // print('❌ WebView resource error: ${error.description} on ${error.failingUrl}'); // Add logging
          },
          onNavigationRequest: (NavigationRequest request) {
            print('🔀 WebView navigation request to: ${request.url}'); // Add logging
            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,
                    ),
                  );
                }),
        ));
  }
}
