import 'dart:io' show Platform;

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/helpers/base_storage.dart' as hub;
import 'package:hub/shared/helpers/storage_helper.dart';
import 'package:hub/shared/utils/webview_util.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:webview_flutter/webview_flutter.dart';

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

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

class _FastPassPageWidgetState extends State<FastPassPageWidget> {
  late WebViewController _controllerAndroid;
  late InAppWebViewController _controllerIOS;

  Future<Map<String, String>> initVariables() async {
    final email = (await StorageHelper().get(hub.SecureStorageKey.email.value, hub.Storage.SecureStorage)) ?? '';
    final name = (await StorageHelper().get(hub.SQLiteStorageKey.userName.value, hub.Storage.SQLiteStorage)) ?? '';
    final devUUID = (await StorageHelper().get(hub.SQLiteStorageKey.devUUID.value, hub.Storage.SQLiteStorage)) ?? '';
    final userUUID = (await StorageHelper().get(hub.SQLiteStorageKey.userUUID.value, hub.Storage.SQLiteStorage)) ?? '';
    final cliUUID = (await StorageHelper().get(hub.SQLiteStorageKey.clientUUID.value, hub.Storage.SQLiteStorage)) ?? '';
    const createdAt = '0000-00-00 00:00:00';
    final url = 'https://hub.freaccess.com.br/hub/fast-pass/$cliUUID';
    final freUserData =
        "{\"name\": \"$name\", \"email\": \"$email\",\"dev_id\": \"$devUUID\",\"created_at\":\"$createdAt\",\"updated_at\": \"0000-00-00 00:00:00\",\"status\": \"A\" }";

    return {
      'url': url,
      'name': name,
      'email': email,
      'userUUID': userUUID,
      'devUUID': devUUID,
      'createdAt': createdAt,
      'cliUUID': cliUUID,
      'freUserData': freUserData,
    };
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: FutureBuilder<Map<String, String>>(
          future: initVariables(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            } else if (snapshot.hasError || snapshot.hasData == false || snapshot.data!.isEmpty) {
              return Center(
                  child: Text(FFLocalizations.of(context)
                      .getVariableText(enText: 'Unexpected error', ptText: 'Erro inesperado')));
            } else if (snapshot.hasData) {
              final data = snapshot.data!;
              final url = data['url']!;
              final userUUID = data['userUUID']!;
              final freUserData = data['freUserData']!;

              return Platform.isIOS
                  ? InAppWebView(
                      initialUrlRequest: URLRequest(url: WebUri(url)),
                      initialSettings: InAppWebViewSettings(
                        allowsBackForwardNavigationGestures: true,
                        javaScriptEnabled: true,
                      ),
                      onWebViewCreated: (controller) async => _controllerIOS = controller,
                      onLoadStop: (controller, url) async {
                        await controller.evaluateJavascript(
                            source: "window.localStorage.setItem('fre-token', '\"$userUUID\"')");
                        await controller.evaluateJavascript(
                            source: "window.localStorage.setItem('fre-user-data', '$freUserData')");
                        await controller.evaluateJavascript(
                            source: "window.localStorage.setItem('enableBackButton', 'true')");
                      },
                      onUpdateVisitedHistory: (controller, uri, isVisited) {
                        if (uri.toString().contains('/hub/home')) context.pop();
                      },
                    )
                  : WebViewWidget(
                      controller: _controllerAndroid = WebViewController()
                        ..clearCache()
                        ..clearLocalStorage()
                        ..setJavaScriptMode(JavaScriptMode.unrestricted)
                        ..setBackgroundColor(const Color(0x00000000))
                        ..setNavigationDelegate(
                          NavigationDelegate(
                              onProgress: (int progress) {},
                              onPageStarted: (String url) {
                                final String token = "localStorage.setItem('fre-token', '\"$userUUID\"');";
                                final String data = "localStorage.setItem('fre-user-data', '$freUserData');";
                                const String backNavigation = "localStorage.setItem('enableBackButton', 'true');";

                                _controllerAndroid.runJavaScript(token);
                                _controllerAndroid.runJavaScript(data);
                                _controllerAndroid.runJavaScript(backNavigation);
                              },
                              onPageFinished: (String url) {
                                bool isDarkMode =
                                    SchedulerBinding.instance.platformDispatcher.platformBrightness == Brightness.dark;

                                if (isDarkMode) {
                                  _controllerAndroid.runJavaScript(WebviewUtil.jsEnableDarkMode);
                                }
                              },
                              onNavigationRequest: (NavigationRequest request) {
                                if (request.url.startsWith('http') ||
                                    request.url.startsWith('https://api.whatsapp.com/send') ||
                                    request.url.startsWith('https://wa.me')) {
                                  launchUrlString(request.url);
                                  return NavigationDecision.prevent;
                                }
                                return NavigationDecision.prevent;
                              },
                              onUrlChange: (url) {
                                if (url.url.toString().contains('/hub/home')) context.pop();
                              }),
                        )
                        ..loadRequest(Uri.parse(url)),
                    );
            } else {
              return const Center(child: Text('Unexpected error'));
            }
          },
        ),
      ),
    );
  }
}
