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

import 'package:boilerplate/presentation/widgets/base_scaffold.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ContactUsPage extends StatefulWidget {
  final String? title;
  final String url;

  ContactUsPage({
    Key? key,
    required this.url,
    this.title,
  }) : super(key: key);

  @override
  State<ContactUsPage> createState() => _ContactUsPageState();
}

class _ContactUsPageState extends State<ContactUsPage> {
  late String lang = '';
  String url = "";
  late Timer _timer;
  int _start = 16;
  bool loading = true;

  getLang() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    setState(() {
      lang = prefs.getString('lang').toString();
    });
    WidgetsFlutterBinding.ensureInitialized();

    if (Platform.isAndroid) {
      await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
    }
    await FirebaseAnalytics.instance.logScreenView(screenName: 'WebviewPage');
  }

  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;
  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
        useShouldOverrideUrlLoading: true,
        mediaPlaybackRequiresUserGesture: false,
      ),
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),
      ios: IOSInAppWebViewOptions(
        allowsInlineMediaPlayback: true,
      ));

  void startTimer() {
    const oneSec = const Duration(seconds: 1);
    _timer = new Timer.periodic(
      oneSec,
      (Timer timer) => setState(
        () {
          if (_start < 1) {
            setState(() {
              loading = false;
            });
            timer.cancel();
          } else {
            _start = _start - 1;
          }
        },
      ),
    );
  }

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

    startTimer();

    getLang();
  }

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      body: loading == true
          ? Center(
              child: CircularProgressIndicator(
                color: Colors.redAccent,
              ),
            )
          : Container(
              height: MediaQuery.of(context).size.height,
              child: InAppWebView(
                key: webViewKey,
                initialUrlRequest: URLRequest(url: Uri.parse("${widget.url}")),
                initialOptions: options,
                onWebViewCreated: (controller) {
                  webViewController = controller;
                },
                onLoadStart: (controller, url) {
                  setState(() {
                    this.url = url.toString();
                  });
                },
                androidOnPermissionRequest:
                    (controller, origin, resources) async {
                  return PermissionRequestResponse(
                      resources: resources,
                      action: PermissionRequestResponseAction.GRANT);
                },
                shouldOverrideUrlLoading: (controller, navigationAction) async {
                  var uri = navigationAction.request.url!;

                  return NavigationActionPolicy.ALLOW;
                },
                onLoadStop: (controller, url) async {},
                onLoadError: (controller, url, code, message) {},
                onProgressChanged: (controller, progress) {
                  if (progress == 100) {
                    // print('onChange ${progress}');
                    setState(() {
                      loading = false;
                    });
                  }
                },
                onUpdateVisitedHistory: (controller, url, androidIsReload) {
                  setState(() {
                    this.url = url.toString();
                  });
                },
                onConsoleMessage: (controller, consoleMessage) {
                  // print(consoleMessage);
                },
              ),
            ),
      title: widget.title,
    );
  }
}
