import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/bloc/app_bloc.dart';
import 'package:hl_lieferservice/data/network/keycloak_oidc_token_provider.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_bloc.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_event.dart';
import 'package:hl_lieferservice/feature/authentication/presentation/login_enforcer.dart';
import 'package:hl_lieferservice/main.dart' show locator;
import 'package:hl_lieferservice/feature/car_selection/bloc/bloc.dart';
import 'package:hl_lieferservice/feature/car_selection/presentation/car_selection_enforcer.dart';
import 'package:hl_lieferservice/feature/car_selection/repository/car_selection_repository.dart';
import 'package:hl_lieferservice/feature/cars/bloc/cars_bloc.dart';
import 'package:hl_lieferservice/feature/cars/presentation/car_management_page.dart';
import 'package:hl_lieferservice/feature/cars/repository/cars_repository.dart';
import 'package:hl_lieferservice/feature/cars/service/cars_service.dart';
import 'package:hl_lieferservice/feature/delivery/bloc/phase_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/bloc/tour_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/bloc/tour_state.dart';
import 'package:hl_lieferservice/feature/delivery/repository/tour_repository.dart';
import 'package:hl_lieferservice/widget/home/bloc/navigation_bloc.dart';
import 'package:hl_lieferservice/widget/operations/bloc/operation_bloc.dart';
import 'package:hl_lieferservice/widget/operations/presentation/operation_view_enforcer.dart';

import 'package:hl_lieferservice/bloc/app_states.dart';
import '../feature/delivery/service/tour_service.dart';
import 'home/presentation/home.dart';

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

  @override
  State<StatefulWidget> createState() => _DeliveryAppState();
}

class _DeliveryAppState extends State<DeliveryApp> {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<AppBloc, AppState>(
      builder: (context, state) {
        if (state is AppConfigLoaded) {
          return MultiBlocProvider(
            providers: [
              BlocProvider(create: (context) => NavigationBloc()),
              BlocProvider(create: (context) => OperationBloc()),
              BlocProvider(
                create:
                    (context) => AuthBloc(
                          tokenProvider:
                              locator<KeycloakOidcTokenProvider>(),
                          operationBloc: context.read<OperationBloc>(),
                        )
                        // Beim ersten Build: prüfen, ob ein
                        // Refresh-Token aus der Secure Storage da ist,
                        // und ggf. direkt einloggen.
                        ..add(const RestoreSessionRequested()),
              ),
              BlocProvider(
                create:
                    (context) => TourBloc(
                      opBloc: context.read<OperationBloc>(),
                      authBloc: context.read<AuthBloc>(),
                      tourRepository: TourRepository(
                        service: TourService(),
                      ),
                    ),
              ),
              BlocProvider(
                create: (context) =>
                    CarSelectBloc(repository: CarSelectionRepository()),
              ),
              BlocProvider(
                create: (context) => CarsBloc(
                  repository: CarsRepository(service: CarService()),
                  opBloc: context.read<OperationBloc>(),
                  authBloc: context.read<AuthBloc>(),
                ),
              ),
              BlocProvider(
                // PhaseBloc darf erst NACH dem TourBloc gebaut werden,
                // da er die Anzahl der Team-Fahrzeuge daraus liest, um
                // beim ersten Load eines Fahrzeugs die korrekte
                // Eintrittsphase (Auswählen vs. Sortieren) zu bestimmen.
                create: (context) => PhaseBloc(
                  carCountResolver: () {
                    final tourState = context.read<TourBloc>().state;
                    return tourState is TourLoaded
                        ? tourState.tour.driver.cars.length
                        : null;
                  },
                ),
              ),
            ],
            child: MaterialApp(
              // Wrap the Navigator (not just the home route) so the loading
              // overlay covers every pushed route — DeliveryDetail, Cars,
              // dialogs, etc. — not only the initial home tree.
              builder: (context, child) =>
                  OperationViewEnforcer(child: child ?? const SizedBox.shrink()),
              home: BlocBuilder<AppBloc, AppState>(
                builder: (context, state) {
                  if (state is AppConfigLoading) {
                    return Scaffold(
                      body: Center(child: CircularProgressIndicator()),
                    );
                  }

                  if (state is AppConfigLoadingFailed) {
                    return Scaffold(body: Center(child: Text(state.message)));
                  }

                  if (state is AppConfigLoaded) {
                    return LoginEnforcer(
                      child: CarSelectionEnforcer(child: Home()),
                    );
                  }

                  return Container();
                },
              ),
              routes: {"/cars": (context) => CarManagementPage()},
            ),
          );
        }

        if (state is AppConfigLoadingFailed) {
          return MaterialApp(
            home: Scaffold(
              body: Center(child: Text("Fehler beim Laden der Konfiguration")),
            ),
          );
        }

        return MaterialApp(
          home: Scaffold(
            body: Center(child: const CircularProgressIndicator()),
          ),
        );
      },
    );
  }
}
