import 'package:ambito/src/config/config.dart';
import 'package:ambito/src/consts/consts.dart';
import 'package:ambito/src/entity/cart/cart.dart';
import 'package:ambito/src/entity/cart/cart_element.dart';
import 'package:ambito/src/entity/cart/cart_repository.dart';
import 'package:ambito/src/entity/lists/list_measure.dart';
import 'package:ambito/src/entity/lists/list_repository.dart';
import 'package:ambito/src/packages/ambito_api/base_api.dart';
import 'package:ambito/src/packages/ambito_db/base_db.dart';
import 'package:ambito/src/packages/ambito_notifier/notifier/theme_manager.dart';
import 'package:ambito/src/packages/ambito_sharedprefs/ambito_sharedprefs.dart';
import 'package:ambito/src/pages/calendar/calendar_page.dart';
import 'package:ambito/src/pages/calendar/calendar_page_year.dart';
import 'package:ambito/src/pages/cart/cart_page.dart';
import 'package:ambito/src/pages/dashboard/areas/dashboard_areas_page.dart';
import 'package:ambito/src/pages/dashboard/dashboard_page.dart';
import 'package:ambito/src/pages/dashboard/master_data/master_data_page.dart';
import 'package:ambito/src/pages/error/error_page.dart';
import 'package:ambito/src/pages/measure/categories/measure_categories_page.dart';
import 'package:ambito/src/pages/measure/create/measure_create_page.dart';
import 'package:ambito/src/pages/measure/detail/measure_detail_page.dart';
import 'package:ambito/src/pages/measure/groups/measure_groups_page.dart';
import 'package:ambito/src/pages/measure/measure_page.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:screen_breakpoints/screen_breakpoints.dart';
import 'package:syncfusion_localizations/syncfusion_localizations.dart';

List<ListMeasure> listMeasures = <ListMeasure>[].toList(growable: true);

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await AmbitoSharedPrefs.start();
  await AmbitoIsarDB.init();
  await Future.wait([
    BaseApi().getContent('measure_types'),
    BaseApi().getContent('measure_types_details'),
    BaseApi().getContent('measure_general'),
    BaseApi().getContent('measure_details'),
    BaseApi().getContent('funding_program'),
    BaseApi().getContent('business'),
    BaseApi().getContent('area'),
    BaseApi().getContent('login'),
  ]);
  List<int> myCartIds = [];

  var carts = await BaseApi().getContent('cart', false);
  for (final cart in carts) {
    CartRepository().put(Cart.fromJson(cart));
  }
  var cartElements = await BaseApi().getContent('cart_element', false);
  for (final element in cartElements) {
    CartRepository().putElement(CartElement.fromJson(element));
  }
  /*for (final cart in carts) {
    if (cart['field_3106997'].first['id'] ==
        (prefs.getInt('currentUser') ?? 100)) {
      logger.i('Found my cart!');
      Cart cartToSave = Cart.fromJson(cart);
      myCartIds.add(cartToSave.id);
      CartRepository().put(cartToSave);
    }
  }*/

  MeasureRepository().buildMeasureComplete();

  /*BaseApi().getContent('cart', false).then((carts) {
    logger.i(carts);
    for (final cart in carts) {
      logger.e(cart);
      if (cart['field_3106997'].first['id'] ==
          (prefs.getInt('currentUser') ?? 100)) {
        logger.i('Found my cart!');
        CartRepository().put(Cart.fromJson(cart));
      }
    }
    logger.e(CartRepository().getAll().length);
  });*/
  ListRepository().buildTypeGroupCategoryList();
  ListRepository().buildListMeasureSingle();
  ListRepository().putListMeasure(listMeasures);

  await MeasureRepository().getCategoriesGroupsAndTypes();

  MeasureRepository().buildMeasureMonths();

  runApp(const Ambito());
}

class Ambito extends StatelessWidget {
  const Ambito({super.key});
  @override
  Widget build(BuildContext context) {
    return BreakpointConfigurator(
      configuration: myBreakpoints,
      child: ChangeNotifierProvider(
        create: (_) => ThemeManager(),
        child: Consumer<ThemeManager>(
            builder: (context, ThemeManager themeManager, child) {
          return GetMaterialApp(
            debugShowCheckedModeBanner: false,
            localizationsDelegates: [
              FlutterI18nDelegate(
                translationLoader: FileTranslationLoader(
                  fallbackFile: 'de',
                  basePath: 'i18n',
                ),
                missingTranslationHandler: (key, locale) {
                  if (kDebugMode) {
                    print("--- Missing Key: $key, languageCode: $locale");
                  }
                },
              ),
              GlobalMaterialLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              SfGlobalLocalizations.delegate,
            ],
            title: 'AmBiTo',
            supportedLocales: supportedLocales,
            locale: ThemeManager().locale,
            builder: FlutterI18n.rootAppBuilder(),
            theme: ThemeManager().themeData?.lightThemeData,
            darkTheme: ThemeManager().themeData?.darkThemeData,
            themeMode: ThemeMode.light,
            initialRoute: '/massnahmen',
            getPages: [
              GetPage(
                name: '/',
                page: () => const MeasureCategoriesPage(),
              ),
              GetPage(
                name: '/warenkorb',
                page: () => const CartPage(
                  measure: null,
                ),
              ),
              GetPage(
                name: '/kalender',
                page: () => const CalendarPage(),
              ),
              GetPage(
                name: '/kalender/jahr',
                page: () => const CalendarPageYear(),
              ),
              GetPage(
                name: '/massnahmen',
                page: () => const MeasureCategoriesPage(),
              ),
              GetPage(
                name: '/massnahmendatenbank',
                page: () => const MeasureCategoriesPage(),
              ),
              GetPage(
                name: '/massnahmendatenbank/:kategorie',
                page: () => const MeasureGroupsPage(),
              ),
              GetPage(
                name: '/massnahmendatenbank/:kategorie/:group',
                page: () => const MeasuresPage(),
              ),
              GetPage(
                name: '/massnahmendatenbank/:kategorie/:group/:type',
                page: () => const MeasuresPage(),
              ),
              GetPage(
                name: '/dashboard',
                page: () => DashboardPage(
                  businessId: prefs.getInt('currentUser') ?? 100,
                  userId: 0,
                ),
              ),
              GetPage(
                name: '/dashboard/meine-massnahmen',
                page: () => DashboardPage(
                  businessId: prefs.getInt('currentUser') ?? 100,
                  userId: 0,
                ),
              ),
              GetPage(
                name: '/dashboard/urkunde',
                page: () => DashboardPage(
                  businessId: prefs.getInt('currentUser') ?? 100,
                  userId: 0,
                ),
              ),
              GetPage(
                name: '/dashboard/flaechen',
                page: () => DashboardAreasPage(
                  businessId: prefs.getInt('currentUser') ?? 100,
                  userId: 0,
                ),
              ),
              GetPage(
                name: '/dashboard/flaechen/:index',
                page: () => DashboardAreasPage(
                  businessId: prefs.getInt('currentUser') ?? 100,
                  userId: 0,
                ),
              ),
              GetPage(
                name: '/dashboard/stammdaten',
                page: () => MasterDataPage(
                  businessId: prefs.getInt('currentUser') ?? 100,
                  userId: 1,
                ),
              ),
              GetPage(
                name: '/massnahme/neu',
                page: () => const MeasureCreatePage(),
              ),
              GetPage(
                name: '/massnahme/:id',
                page: () => const MeasureDetailPage(),
              ),
              GetPage(
                name: '/error',
                page: () => const ErrorPage(),
              ),
            ],
          );
        }),
      ),
    );
  }
}
