import 'dart:async';
import 'dart:developer';
import 'dart:ui';
import 'package:enaklo_pos/core/constants/theme.dart';
import 'package:enaklo_pos/core/network/dio_client.dart';
import 'package:enaklo_pos/data/datasources/analytic_remote_datasource.dart';
import 'package:enaklo_pos/data/datasources/customer_remote_datasource.dart';
import 'package:enaklo_pos/data/datasources/file_remote_datasource.dart';
import 'package:enaklo_pos/data/datasources/outlet/outlet_remote_data_source.dart';
import 'package:enaklo_pos/data/datasources/table_remote_datasource.dart';
import 'package:enaklo_pos/data/datasources/user_remote_datasource.dart';
import 'package:enaklo_pos/presentation/customer/bloc/customer_form/customer_form_bloc.dart';
import 'package:enaklo_pos/presentation/customer/bloc/customer_loader/customer_loader_bloc.dart';
import 'package:enaklo_pos/presentation/data_sync/bloc/data_sync_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/category_loader/category_loader_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/current_outlet/current_outlet_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/order_form/order_form_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/outlet_loader/outlet_loader_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/product_loader/product_loader_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/user_update_outlet/user_update_outlet_bloc.dart';
import 'package:enaklo_pos/presentation/refund/bloc/refund_bloc.dart';
import 'package:enaklo_pos/presentation/report/blocs/category_report/category_report_bloc.dart';
import 'package:enaklo_pos/presentation/report/blocs/inventory_report/inventory_report_bloc.dart';
import 'package:enaklo_pos/presentation/report/blocs/profit_loss/profit_loss_bloc.dart';
import 'package:enaklo_pos/presentation/report/blocs/report/report_bloc.dart';
import 'package:enaklo_pos/presentation/sales/blocs/order_loader/order_loader_bloc.dart';
import 'package:enaklo_pos/presentation/sales/blocs/payment_form/payment_form_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/get_printer_ticket/get_printer_ticket_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/upload_file/upload_file_bloc.dart';
import 'package:enaklo_pos/presentation/table/blocs/transfer_table/transfer_table_bloc.dart';
import 'package:enaklo_pos/presentation/void/bloc/void_order_bloc.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/material.dart';
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
import 'package:enaklo_pos/data/datasources/auth_remote_datasource.dart';
import 'package:enaklo_pos/data/datasources/category/category_remote_datasource.dart';
import 'package:enaklo_pos/data/datasources/discount_remote_datasource.dart';
import 'package:enaklo_pos/data/datasources/midtrans_remote_datasource.dart';
import 'package:enaklo_pos/data/datasources/order_remote_datasource.dart';
import 'package:enaklo_pos/data/datasources/product_remote_datasource.dart';
import 'package:enaklo_pos/data/datasources/payment_methods_remote_datasource.dart';
import 'package:enaklo_pos/data/datasources/settings_local_datasource.dart';
import 'package:enaklo_pos/presentation/auth/bloc/logout/logout_bloc.dart';
import 'package:enaklo_pos/presentation/auth/login_page.dart';
import 'package:enaklo_pos/presentation/home/bloc/get_table_status/get_table_status_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/online_checker/online_checker_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/payment_methods/payment_methods_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/qris/qris_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/checkout/checkout_bloc.dart';
import 'package:enaklo_pos/presentation/report/blocs/item_sales_report/item_sales_report_bloc.dart';
import 'package:enaklo_pos/presentation/report/blocs/payment_method_report/payment_method_report_bloc.dart';
import 'package:enaklo_pos/presentation/report/blocs/product_sales/product_sales_bloc.dart';
import 'package:enaklo_pos/presentation/report/blocs/summary/summary_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/add_product/add_product_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/create_printer/create_printer_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/get_categories/get_categories_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/get_printer_bar/get_printer_bar_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/get_printer_checker/get_printer_checker_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/get_products/get_products_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/update_product/update_product_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/update_printer/update_printer_bloc.dart';
import 'package:enaklo_pos/presentation/table/blocs/change_position_table/change_position_table_bloc.dart';
import 'package:enaklo_pos/presentation/table/blocs/create_table/create_table_bloc.dart';
import 'package:enaklo_pos/presentation/table/blocs/get_table/get_table_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/order/order_bloc.dart';
import 'package:enaklo_pos/presentation/report/blocs/transaction_report/transaction_report_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/add_discount/add_discount_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/discount/discount_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/sync_product/sync_product_bloc.dart';
import 'package:enaklo_pos/presentation/setting/bloc/tax_settings/tax_settings_bloc.dart';
import 'package:enaklo_pos/presentation/table/blocs/update_table/update_table_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/add_order_items/add_order_items_bloc.dart';
import 'presentation/auth/bloc/login/login_bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'presentation/home/pages/dashboard_page.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

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

    await Firebase.initializeApp();
    await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);

    // ✅ Tambah custom logs
    FlutterError.onError = (errorDetails) {
      FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
    };

    // ✅ Catch platform errors juga
    PlatformDispatcher.instance.onError = (error, stack) {
      FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
      return true;
    };

    runApp(ProviderScope(child: MyApp()));
  }, (error, stack) {
    // ✅ Ini udah bener
    FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
  });
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // This widget is the root of your application.
  // final iminPrinter = IminPrinter();
  String version = '1.0.0';
  @override
  void initState() {
    super.initState();
    getSdkVersion();
  }

  Future<void> getSdkVersion() async {
    // final sdkVersion = await iminPrinter.getSdkVersion();
    if (!mounted) return;
    // setState(() {
    //   version = sdkVersion!;
    // });
  }

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (context) => LoginBloc(AuthRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => LogoutBloc(AuthRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => SyncProductBloc(ProductRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) =>
              CheckoutBloc(settingsLocalDatasource: SettingsLocalDatasource()),
        ),
        BlocProvider(
          create: (context) => TaxSettingsBloc(SettingsLocalDatasource()),
        ),
        BlocProvider(
          create: (context) {
            log("🔧 main.dart: Creating OrderBloc instance");
            return OrderBloc(OrderRemoteDatasource());
          },
        ),
        BlocProvider(
          create: (context) => DiscountBloc(DiscountRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => AddDiscountBloc(DiscountRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => TransactionReportBloc(OrderRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => CreateTableBloc(TableRemoteDataSource()),
        ),
        BlocProvider(
          create: (context) => ChangePositionTableBloc(TableRemoteDataSource()),
        ),
        BlocProvider(
          create: (context) => GetTableBloc(TableRemoteDataSource()),
        ),
        BlocProvider(
          create: (context) => UpdateTableBloc(),
        ),
        BlocProvider(
          create: (context) => GetTableStatusBloc(TableRemoteDataSource()),
        ),
        BlocProvider(
          create: (context) => AddProductBloc(ProductRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => UpdateProductBloc(ProductRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => GetProductsBloc(ProductRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => GetCategoriesBloc(CategoryRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => SummaryBloc(AnalyticRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => ProfitLossBloc(AnalyticRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => ProductSalesBloc(AnalyticRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => ItemSalesReportBloc(AnalyticRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) =>
              PaymentMethodReportBloc(AnalyticRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => QrisBloc(MidtransRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) =>
              PaymentMethodsBloc(PaymentMethodsRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => OnlineCheckerBloc(),
        ),
        BlocProvider(
          create: (context) => CreatePrinterBloc(),
        ),
        BlocProvider(
          create: (context) => UpdatePrinterBloc(),
        ),
        BlocProvider(
          create: (context) => GetPrinterReceiptBloc(),
        ),
        BlocProvider(
          create: (context) => GetPrinterCheckerBloc(),
        ),
        BlocProvider(
          create: (context) => GetPrinterKitchenBloc(),
        ),
        BlocProvider(
          create: (context) => GetPrinterBarBloc(),
        ),
        BlocProvider(
          create: (context) => AddOrderItemsBloc(OrderRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => ProductLoaderBloc(),
        ),
        BlocProvider(
          create: (context) => OrderFormBloc(OrderRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => OrderLoaderBloc(OrderRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => OutletLoaderBloc(OutletRemoteDataSource()),
        ),
        BlocProvider(
          create: (context) => CustomerLoaderBloc(CustomerRemoteDataSource()),
        ),
        BlocProvider(
          create: (context) => CustomerFormBloc(CustomerRemoteDataSource()),
        ),
        BlocProvider(
          create: (context) => PaymentFormBloc(OrderRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => CurrentOutletBloc(OutletRemoteDataSource()),
        ),
        BlocProvider(
          create: (context) => VoidOrderBloc(OrderRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => RefundBloc(OrderRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => UserUpdateOutletBloc(UserRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => UploadFileBloc(FileRemoteDataSource()),
        ),
        BlocProvider(
          create: (context) => CategoryLoaderBloc(),
        ),
        BlocProvider(
          create: (context) => GetPrinterTicketBloc(),
        ),
        BlocProvider(
          create: (context) => TransferTableBloc(TableRemoteDataSource()),
        ),
        BlocProvider(
          create: (context) => ReportBloc(AnalyticRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => InventoryReportBloc(AnalyticRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => CategoryReportBloc(AnalyticRemoteDatasource()),
        ),
        BlocProvider(
          create: (context) => DataSyncBloc(),
        ),
      ],
      child: MaterialApp(
        navigatorKey: AuthInterceptor.navigatorKey,
        debugShowCheckedModeBanner: false,
        title: 'POS Resto App',
        theme: getApplicationTheme,
        home: FutureBuilder<bool>(
            future: AuthLocalDataSource().isAuthDataExists(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Scaffold(
                  body: Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              }
              if (snapshot.hasData) {
                if (snapshot.data!) {
                  return const DashboardPage();
                } else {
                  return const LoginPage();
                }
              }
              return const Scaffold(
                body: Center(
                  child: Text('Error'),
                ),
              );
            }),
      ),
    );
  }
}
