import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:connectivity_plus/connectivity_plus.dart';

import 'package:marco/helpers/services/app_initializer.dart';
import 'package:marco/view/my_app.dart';
import 'package:marco/helpers/theme/app_notifier.dart';
import 'package:marco/helpers/services/app_logger.dart';
import 'package:marco/view/layouts/offline_screen.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await initLogging();
  logSafe("App starting...");
  enableRemoteLogging();
  try {
    await initializeApp();
    logSafe("App initialized successfully.");

    runApp(
      ChangeNotifierProvider(
        create: (_) => AppNotifier(),
        child: const MainWrapper(),
      ),
    );
  } catch (e, stacktrace) {
    logSafe(
      'App failed to initialize.',
      level: LogLevel.error,
      error: e,
      stackTrace: stacktrace,
    );
    runApp(_buildErrorApp());
  }
}

Widget _buildErrorApp() => const MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text(
            "Failed to initialize the app.",
            style: TextStyle(color: Colors.red),
          ),
        ),
      ),
    );

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

  @override
  State<MainWrapper> createState() => _MainWrapperState();
}

class _MainWrapperState extends State<MainWrapper> {
  List<ConnectivityResult> _connectivityStatus = [ConnectivityResult.none];
  final Connectivity _connectivity = Connectivity();

  @override
  void initState() {
    super.initState();
    _initializeConnectivity();
    _connectivity.onConnectivityChanged.listen((results) {
      setState(() => _connectivityStatus = results);
    });
  }

  Future<void> _initializeConnectivity() async {
    final result = await _connectivity.checkConnectivity();
    setState(() => _connectivityStatus = result);
  }

  @override
  Widget build(BuildContext context) {
    final bool isOffline =
        _connectivityStatus.contains(ConnectivityResult.none);
    return isOffline
        ? const MaterialApp(
            debugShowCheckedModeBanner: false, home: OfflineScreen())
        : const MyApp();
  }
}
