import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:quickquiz/loading/loading_screen.dart';
import 'package:quickquiz/ui/widgets/common_scaffold.dart';

class NoNetworkL extends StatefulWidget {
  final String? name;

  NoNetworkL({Key? key, this.name}) : super(key: key);

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

class NoNetworkLState extends State<NoNetworkL> {
  var refreshKey = GlobalKey<RefreshIndicatorState>();
  final scaffoldKey = new GlobalKey<ScaffoldState>();
  final formKey = new GlobalKey<FormState>();

  List<ConnectivityResult> _connectionStatus = [ConnectivityResult.none];
  final Connectivity _connectivity = Connectivity();
  late StreamSubscription<List<ConnectivityResult>> _connectivitySubscription;

  @override
  void initState() {
    super.initState();
    initConnectivity();
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initConnectivity() async {
    late List<ConnectivityResult> result;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      log('Couldn\'t check connectivity status', error: e);
      return;
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) {
      return Future.value(null);
    }

    return _updateConnectionStatus(result);
  }

  Future<void> _updateConnectionStatus(List<ConnectivityResult> result) async {
    setState(() {
      _connectionStatus = result;
    });

    print(_connectionStatus);
    if (result[0] == ConnectivityResult.wifi ||
        result[0] == ConnectivityResult.mobile) {
      var router = new MaterialPageRoute(
          builder: (BuildContext context) => new LoadingScreen());
      Navigator.of(context).push(router);
    } else {
      setState(() {});
    }
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

  Future<String?> getData() async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        var router = new MaterialPageRoute(
            builder: (BuildContext context) => new LoadingScreen());
        Navigator.of(context).push(router);
      }
    } on SocketException catch (_) {
      print('not connected');
    }
    return null;
  }

  Widget bodyData() {
    return new Scaffold(
      backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
      appBar: AppBar(
        elevation: defaultTargetPlatform == TargetPlatform.android ? 0.0 : 0.0,
        backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
        title: Text("QuickQuiz"),
        centerTitle: true,
        automaticallyImplyLeading: false,
      ),
      body: RefreshIndicator(
        key: formKey,
        // child:  Scaffold(
        child: Container(
          alignment: Alignment.center,
          padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
          child: Center(
            child: new ListView(
              children: <Widget>[
                new Container(
                  child: new Column(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Text(
                        "Check Network Connection",
                        style: new TextStyle(
                          color: Colors.red,
                          fontSize: 20.0,
                        ),
                      ),
                      SizedBox(
                        height: 30.0,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        // ),
        onRefresh: refreshList,
      ),
    );
  }

  Future<Null> refreshList() async {
    refreshKey.currentState?.show(atTop: true);
    await Future.delayed(Duration(seconds: 2));
    getData();
  }

  Widget _scaffold() => CommonScaffold(
        scaffoldKey: scaffoldKey,
        bodyData: bodyData(),
        floatBtn: false,
      );

  @override
  Widget build(BuildContext context) {
    return _scaffold();

    // return
  }
}
