import 'package:flutter/material.dart';
import 'package:school_management_system/components/default_values.dart';
import 'package:school_management_system/screens/welcome/welcome_screen.dart';
import 'package:webview_flutter/webview_flutter.dart';

late Future<bool> _checkToken;

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  late final WebViewController controller;
  var loadingPercentage = 0;
//  String? message;

  // setMessage(String javascriptMessage) {
  //   if (mounted) {
  //     setState(() {
  //       message = javascriptMessage;
  //     });
  //   }
  // }

  @override
  void initState() {
    _checkToken = checkTokenValidity();
    super.initState();
    controller = WebViewController()
      ..loadRequest(
        Uri.parse('https://www.tees.ac.uk/sections/stud/news.cfm'),
      )
      // ..addJavaScriptChannel("myChannel",
      //     onMessageReceived: (JavaScriptMessage message) {
      //   //  setMessage(message.message);
      // })
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(NavigationDelegate(
        onPageStarted: (url) {
          setState(() {
            loadingPercentage = 0;
          });
        },
        onProgress: (progress) {
          setState(() {
            loadingPercentage = progress;
          });
        },
        onPageFinished: (url) {
          setState(() {
            loadingPercentage = 100;
          });
        },
      ));
  }

  @override
  Widget build(BuildContext context) {
    _checkToken.then(
      (value) {
        if (!value) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) {
                return const WelcomeScreen();
              },
            ),
          );

          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Session Time Out / Sign Back In'),
            ),
          );
        }
      },
    );

    return Stack(
      children: [
        WebViewWidget(
          controller: controller,
        ),
        if (loadingPercentage < 100)
          LinearProgressIndicator(
            value: loadingPercentage / 100.0,
          ),
      ],
    );
  }
}
