import 'dart:ui';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:get/get.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:terepi_seged/pages/tracking/presentation/controllers/tracking_controller.dart';
import 'package:terepi_seged/routes/app_pages.dart';
import 'package:terepi_seged/services/app_database.dart';
import 'package:terepi_seged/services/app_logger.dart';
import 'package:terepi_seged/services/auth_service.dart';
import 'package:terepi_seged/services/contact_service.dart';
import 'package:terepi_seged/services/coord_converter_service.dart';
import 'package:terepi_seged/services/device_identity_service.dart';
import 'package:terepi_seged/services/firebase_logger.dart';
import 'package:terepi_seged/services/gnss/gnss_device_service.dart';
import 'package:terepi_seged/services/gnss/gnss_service.dart';
import 'package:terepi_seged/services/layer_import_service.dart';
import 'package:terepi_seged/services/layer_sync_service.dart';
import 'package:terepi_seged/services/note_audio_service.dart';
import 'package:terepi_seged/services/note_photo_service.dart';
import 'package:terepi_seged/services/ntrip_service.dart';
import 'package:terepi_seged/services/permission_service.dart';
import 'package:terepi_seged/services/project_service.dart';
import 'package:terepi_seged/services/stakeout_service.dart';
import 'package:terepi_seged/services/stakeout_sync_service.dart';
import 'package:terepi_seged/services/tilt_service.dart';
import 'package:terepi_seged/services/track_sync_service.dart';
import 'package:terepi_seged/services/ts_sync_service.dart';

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

  FlutterError.onError = (details) {
    FlutterError.presentError(details);
    FirebaseCrashlytics.instance.recordFlutterFatalError(details);
  };

  PlatformDispatcher.instance.onError = (error, stack) {
    // A Supabase session-automata frissítése saját háttér-időzítővel fut;
    // terepen, jel nélkül ez RENDSZERESEN SocketException/
    // AuthRetryableFetchException-nel száll el — ez NEM app-összeomlás,
    // a GoTrue a következő ciklusban magától újrapróbálja. A saját,
    // explicit bejelentkezési hívásainkat már helyben elkapjuk
    // (AuthService.signInWithGoogle), ezért ide csak ez az ártalmatlan,
    // háttér-eredetű eset juthat el — nem fatal-ként rögzítjük, hogy ne
    // torzítsa a crash-free arányt és ne riasszon feleslegesen.
    if (error is AuthException) {
      FirebaseCrashlytics.instance.recordError(error, stack, fatal: false);
      return true;
    }
    FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
    return true;
  };

  await dotenv.load(fileName: ".env");

  await Supabase.initialize(
      url: dotenv.env['SUPABASE_URL']!,
      anonKey: dotenv.env['SUPABASE_ANON_KEY']!);

  Get.put(AuthService());
  Get.put(DeviceIdentityService(), permanent: true);
  await AppDatabase.instance.database;
  //await AppDatabase.instance.testOnly();
  Get.put(ProjectService(), permanent: true);

  Get.put(AppLogger(), permanent: true);
  Get.put(FirebaseLogger(), permanent: true);
  await Get.putAsync<CoordConverterService>(
      () => CoordConverterService().init());
  Get.put(GnssDeviceService());
  Get.put(GnssService());
  Get.put(StakeoutService());
  Get.put(NtripService());
  NtripService.to.onRtcmData = (data) => GnssService.to.sendToReceiver(data);
  Get.put(TrackingController(), permanent: true);
  Get.put(NotePhotoService(), permanent: true);
  Get.put(NoteAudioService(), permanent: true);
  Get.put(LayerImportService(), permanent: true);
  Get.put(TrackSyncService(), permanent: true);
  Get.put(LayerSyncService());
  Get.put(StakeoutSyncService());
  Get.put(TsSyncService());
  Get.put(TiltService());
  Get.put(PermissionService());
  Get.put(ContactService());

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(useMaterial3: true, colorSchemeSeed: Colors.blue[600]),
      enableLog: true,
      initialRoute: AppPages.INITIAL,
      getPages: AppPages.routes,
    );
  }
}
