import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_bloc.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_state.dart';
import 'package:hl_lieferservice/feature/car_selection/bloc/bloc.dart';
import 'package:hl_lieferservice/feature/car_selection/bloc/events.dart';
import 'package:hl_lieferservice/feature/car_selection/bloc/state.dart';
import 'package:hl_lieferservice/feature/car_selection/presentation/car_selection_page.dart';

class CarSelectionEnforcer extends StatefulWidget {
  final Widget child;

  const CarSelectionEnforcer({super.key, required this.child});

  @override
  State<CarSelectionEnforcer> createState() => _CarSelectionEnforcerState();
}

class _CarSelectionEnforcerState extends State<CarSelectionEnforcer> {
  @override
  void initState() {
    super.initState();
    final authState = context.read<AuthBloc>().state;
    if (authState is Authenticated) {
      context
          .read<CarSelectBloc>()
          .add(CarSelectLoad(userId: authState.user.number));
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CarSelectBloc, CarSelectState>(
      builder: (context, state) {
        // Show a full-screen spinner only while the persisted selection is
        // being read from SharedPreferences (at most one frame on cold start).
        if (state is CarSelectInitial || state is CarSelectLoading) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator()),
          );
        }

        if (state is CarSelectFailed) {
          return Scaffold(
            body: Center(
              child: Padding(
                padding: const EdgeInsets.all(32),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.error_outline,
                      size: 72,
                      color: Theme.of(context).colorScheme.error,
                    ),
                    const SizedBox(height: 24),
                    const Text(
                      "Fehler beim Laden der Fahrzeugauswahl.",
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 16),
                    FilledButton(
                      onPressed: () {
                        final authState = context.read<AuthBloc>().state;
                        if (authState is Authenticated) {
                          context.read<CarSelectBloc>().add(
                                CarSelectLoad(userId: authState.user.number),
                              );
                        }
                      },
                      child: const Text("Erneut versuchen"),
                    ),
                  ],
                ),
              ),
            ),
          );
        }

        // For both CarSelectRequired and CarSelectComplete, keep Home alive
        // in the widget tree so initState is never re-triggered. The selection
        // page is overlaid on top when a (re-)selection is required.
        return Stack(
          children: [
            widget.child,
            if (state is CarSelectRequired)
              Positioned.fill(
                child: CarSelectionPage(previousCar: state.previousCar),
              ),
          ],
        );
      },
    );
  }
}
