import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/feature/car_selection/repository/car_selection_repository.dart';
import 'package:hl_lieferservice/feature/cars/model/selection.dart';
import 'package:hl_lieferservice/domain/entity/car.dart';

import 'events.dart';
import 'state.dart';

class CarSelectBloc extends Bloc<CarSelectEvent, CarSelectState> {
  final CarSelectionRepository repository;

  CarSelectBloc({required this.repository}) : super(CarSelectInitial()) {
    on<CarSelectLoad>(_load);
    on<CarSelectConfirm>(_confirm);
    on<CarSelectChange>(_change);
    on<CarSelectCancel>(_cancel);
  }

  Future<void> _load(
    CarSelectLoad event,
    Emitter<CarSelectState> emit,
  ) async {
    try {
      emit(CarSelectLoading());

      final CarSelection? stored = await repository.getSelection(event.userId);
      final today = DateTime.now();

      final bool validForToday =
          stored != null &&
          stored.selectedCarId != null &&
          stored.selectedCarPlate != null &&
          stored.date.year == today.year &&
          stored.date.month == today.month &&
          stored.date.day == today.day;

      if (validForToday) {
        emit(
          CarSelectComplete(
            selectedCar: Car(
              id: stored.selectedCarId!,
              // accountId/active fließen aus der lokalen Selection
              // nicht durch — wir persistieren nur (id, plate) als
              // UI-Pointer. Die Tour-Logik holt die vollständigen
              // Car-Felder weiterhin aus dem CarsBloc-Listing.
              accountId: 0,
              plate: stored.selectedCarPlate!,
              active: true,
            ),
          ),
        );
      } else {
        emit(CarSelectRequired());
      }
    } catch (e, st) {
      debugPrint('CarSelectBloc._load failed: $e');
      debugPrint('Stacktrace: $st');
      emit(CarSelectFailed());
    }
  }

  void _change(CarSelectChange event, Emitter<CarSelectState> emit) {
    final previousCar =
        state is CarSelectComplete ? (state as CarSelectComplete).selectedCar : null;
    emit(CarSelectRequired(previousCar: previousCar));
  }

  void _cancel(CarSelectCancel event, Emitter<CarSelectState> emit) {
    // Restore without touching SharedPreferences — no tour reload needed.
    emit(CarSelectComplete(selectedCar: event.car));
  }

  Future<void> _confirm(
    CarSelectConfirm event,
    Emitter<CarSelectState> emit,
  ) async {
    try {
      final today = DateTime.now();
      await repository.saveSelection(
        event.userId,
        CarSelection(
          date: today,
          selectedCarId: event.car.id,
          selectedCarPlate: event.car.plate,
        ),
      );
      emit(CarSelectComplete(selectedCar: event.car));
    } catch (e, st) {
      debugPrint('CarSelectBloc._confirm failed: $e');
      debugPrint('Stacktrace: $st');
      emit(CarSelectFailed());
    }
  }
}