import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_background/flutter_background.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:habitrack_app/infrastructure/routing.dart';
import 'package:habitrack_app/sembast/global_providers.dart';
import 'package:logger/logger.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sembast/sembast_io.dart';
import 'package:sembast_web/sembast_web.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  if (kIsWeb) {
    final factory = databaseFactoryWeb;
    final db = await factory.openDatabase('test');
    runApp(
      ProviderScope(
        overrides: [databaseProvider.overrideWithValue(db)],
        child: const MainApp(),
      ),
    );
    // running on the web!
  } else {
    final appPath = await getApplicationDocumentsDirectory();

    appPath.createSync(recursive: true);
    final dbPath = join(appPath.path, 'widgets.db');
    final database = await databaseFactoryIo.openDatabase(dbPath);
    const androidConfig = FlutterBackgroundAndroidConfig(
      notificationTitle: 'flutter_background example app',
      notificationText:
          // ignore: lines_longer_than_80_chars
          'Background notification for keeping the example app running in the background',
      notificationIcon: AndroidResource(
        name: 'background_icon',
        // ignore: avoid_redundant_argument_values
        defType: 'drawable',
      ), // Default is ic_launcher from folder mipmap
    );

    await FlutterBackground.initialize(androidConfig: androidConfig);
    await FlutterBackground.enableBackgroundExecution();

    runApp(
      ProviderScope(
        overrides: [
          databaseProvider.overrideWithValue(database),
        ],
        child: const MainApp(),
      ),
    );
  }
}

Logger logger = Logger();

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      title: 'Habitrack',
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        useMaterial3: true,
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.purple,
        ),
        textTheme: const TextTheme(
          displayLarge: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.amber,
          ),
        ),
      ),
      routerConfig: goRouter,
    );
  }
}
