import 'dart:developer';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:tp5/core/my_theme.dart';
import 'package:tp5/providers/airports.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:flutter/material.dart';
import 'package:tp5/core/core.dart';
import 'package:timezone/data/latest.dart' as tz;

main() async {
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  // FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);

  await Permission.mediaLibrary.onDeniedCallback(() {
    // Your code
  }).onGrantedCallback(() {
    // Your code
  }).onPermanentlyDeniedCallback(() {
    // Your code
  }).onRestrictedCallback(() {
    // Your code
  }).onLimitedCallback(() {
    // Your code
  }).onProvisionalCallback(() {
    // Your code
  }).request();

  // await Permission.manageExternalStorage.onDeniedCallback(() {
  //   // Your code
  // }).onGrantedCallback(() {
  //   // Your code
  // }).onPermanentlyDeniedCallback(() {
  //   // Your code
  // }).onRestrictedCallback(() {
  //   // Your code
  // }).onLimitedCallback(() {
  //   // Your code
  // }).onProvisionalCallback(() {
  //   // Your code
  // }).request();

  // await Permission.storage.onDeniedCallback(() {
  //   // Your code
  // }).onGrantedCallback(() {
  //   // Your code
  // }).onPermanentlyDeniedCallback(() {
  //   // Your code
  // }).onRestrictedCallback(() {
  //   // Your code
  // }).onLimitedCallback(() {
  //   // Your code
  // }).onProvisionalCallback(() {
  //   // Your code
  // }).request();

  await Hive.initFlutter();
  await Hive.openBox("crewlink");
  await Hive.openBox("lido");
  await Hive.openBox("settings");
  await Hive.openBox("settings");

  await PathTo().initialize();

  await Airports.init();

  tz.initializeTimeZones();

  try {
    Supabase.initialize(
        url: 'http://baas.fares.cyou:8000',
        anonKey:
            'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJhbm9uIiwKICAgICJpc3MiOiAic3VwYWJhc2UtZGVtbyIsCiAgICAiaWF0IjogMTY0MTc2OTIwMCwKICAgICJleHAiOiAxNzk5NTM1NjAwCn0.dc_X5iR_VP_qT0zsiyj_I_OZ2T9FtRU2BBNWN8Bu4GE',
        debug: true);
  } catch (e) {
    log("Supabase: $e");
  }
  // FlutterNativeSplash.remove();

  runApp(const ProviderScope(child: MyApp()));
}

class MyApp extends ConsumerWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final routes = ref.read(routeProvider);
    return MaterialApp.router(
      title: 'TAR Pilot',
      debugShowCheckedModeBanner: false,
      theme: myTheme(context, false),
      darkTheme: myTheme(context, true),
      themeMode: ref.watch(appThemeProvider) ? ThemeMode.dark : ThemeMode.light,
      routerConfig: routes,
    );
  }
}
