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/features/storage/index.dart';
import 'package:hub/flutter_flow/internationalization.dart';
import 'package:hub/flutter_flow/nav/nav.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 ReservationPageWidget extends StatefulWidget {
  const ReservationPageWidget({super.key});

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

class _ReservationPageWidgetState extends State<ReservationPageWidget> {
  late WebViewController _controllerAll;

  Future<Map<String, String>> initVariables() async {
    final email =
        (await StorageHelper().get(SecureStorageKey.email.value)) ?? '';
    final name =
        (await StorageHelper().get(ProfileStorageKey.userName.key)) ?? '';
    final devUUID =
        (await StorageHelper().get(ProfileStorageKey.devUUID.key)) ?? '';
    final userUUID =
        (await StorageHelper().get(ProfileStorageKey.userUUID.key)) ?? '';
    final clientId =
        (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';
    const createdAt = '0000-00-00 00:00:00';
    final url = 'https://hub.freaccess.com.br/hub/reservation/$clientId';
    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,
      'clientId': clientId,
      '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 const Center(child: CircularProgressIndicator());
            } else if (snapshot.hasError ||
                !snapshot.hasData ||
                snapshot.data!.isEmpty) {
              return Center(
                  child: Text(FFLocalizations.of(context).getVariableText(
                      enText: 'Unexpected error', ptText: 'Erro inesperado')));
            } else {
              final data = snapshot.data!;
              final url = data['url']!;
              final userUUID = data['userUUID']!;
              final freUserData = data['freUserData']!;
              return Platform.isIOS
                  ? _buildIOSWebView(url, userUUID, freUserData)
                  : _buildAndroidWebView(url, userUUID, freUserData);
            }
          },
        ),
      ),
    );
  }

  Widget _buildIOSWebView(String url, String userUUID, String freUserData) {
    return InAppWebView(
      initialUrlRequest: URLRequest(url: WebUri(url)),
      initialSettings: InAppWebViewSettings(
        allowsBackForwardNavigationGestures: true,
        javaScriptEnabled: true,
      ),
      onWebViewCreated: (controller) async {},
      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();
      },
    );
  }

  Widget _buildAndroidWebView(String url, String userUUID, String freUserData) {
    return WebViewWidget(
      controller: _controllerAll = WebViewController()
        ..clearCache()
        ..clearLocalStorage()
        ..setJavaScriptMode(JavaScriptMode.unrestricted)
        ..setBackgroundColor(const Color(0x00000000))
        ..setNavigationDelegate(
          NavigationDelegate(
            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');";

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

              if (isDarkMode) {
                _controllerAll.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)),
    );
  }
}
