import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class SsoLoginWebView extends StatefulWidget {
  final String? url;
  final String? jwtToken;

  SsoLoginWebView({this.url, this.jwtToken});

  @override
  State<SsoLoginWebView> createState() => _SsoLoginWebViewState();
}

class _SsoLoginWebViewState extends State<SsoLoginWebView> {
  late final WebViewController _controller;
  String? url;
  @override
  void initState() {
    // TODO: implement initState

    url = widget.url ?? "https://Paxes-release.techmaster.in/SSO/HMG";

    super.initState();
    _controller =
        WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setNavigationDelegate(
            NavigationDelegate(
              onProgress: (int progress) {
                print("WebView is loading (progress: $progress%)");
              },
              onPageStarted: (String url) {
                print("Page started loading: $url");
              },
              onPageFinished: (String url) {
                print("Page finished loading: $url");
              },
              onHttpError: (HttpResponseError error) {
                print("HTTP error: ${error.toString()} for URL: ${error.response!.statusCode}");
              },
              onWebResourceError: (WebResourceError error) {
                print("Web resource error: ${error.description} for URL: ${error.errorType}");
              },
            ),
          )
          ..loadHtmlString(''' 
       <!DOCTYPE html>
<html>
<body onload="document.forms[0].submit()">
<form method="POST" action="$url">
<input type="hidden" name="JWTToken" value="${widget.jwtToken}" />
</form>
<h1>Redirecting...</h1>
</body>
</html>''');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: null, body:SafeArea(child:  WebViewWidget(controller: _controller)));
  }
}
