import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../integrations/mattermost/mattermost_push_host_integration.dart';
import '../integrations/mattermost/mattermost_push_plugin_client.dart';
import 'app.dart';

class AltClientBootstrapOptions {
  final bool enablePush;
  final bool applyFullscreen;
  final Future<void> Function()? firebaseInitializer;
  final MattermostPushHostIntegration Function()? mattermostHostFactory;

  const AltClientBootstrapOptions({
    this.enablePush = false,
    this.applyFullscreen = true,
    this.firebaseInitializer,
    this.mattermostHostFactory,
  });
}

MattermostPushHostIntegration _createDefaultMattermostPushHost() {
  return MattermostPushHostIntegration(
    pushClient: MattermostPushPluginClient(),
  );
}

Future<void> applyFullscreenMode() async {
  await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      systemNavigationBarColor: Colors.transparent,
      systemNavigationBarDividerColor: Colors.transparent,
    ),
  );
}

Future<MattermostPushHostIntegration?> bootstrapAltClient({
  AltClientBootstrapOptions options = const AltClientBootstrapOptions(),
}) async {
  if (options.applyFullscreen) {
    await applyFullscreenMode();
  }
  if (!options.enablePush) return null;

  if (options.firebaseInitializer != null) {
    await options.firebaseInitializer!();
  } else {
    await Firebase.initializeApp();
  }

  final host = options.mattermostHostFactory != null
      ? options.mattermostHostFactory!()
      : _createDefaultMattermostPushHost();

  await host.initialize();
  return host;
}

Future<void> runAltClient({
  AltClientBootstrapOptions options = const AltClientBootstrapOptions(),
  void Function(Widget app)? runAppOverride,
}) async {
  WidgetsFlutterBinding.ensureInitialized();
  final mattermostHost = await bootstrapAltClient(options: options);
  final app = ProviderScope(
    child: AltClientApp(mattermostHost: mattermostHost),
  );
  if (runAppOverride != null) {
    runAppOverride(app);
  } else {
    runApp(app);
  }
}

