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_event.dart';
import 'package:hl_lieferservice/feature/authentication/exceptions.dart';
import 'package:hl_lieferservice/feature/cars/repository/cars_repository.dart';
import 'package:hl_lieferservice/widget/operations/bloc/operation_bloc.dart';
import 'package:hl_lieferservice/widget/operations/bloc/operation_event.dart';

import '../../../model/car.dart';
import 'cars_event.dart';
import 'cars_state.dart';

class CarsBloc extends Bloc<CarEvents, CarsState> {
  CarsRepository repository;
  OperationBloc opBloc;
  AuthBloc authBloc;

  CarsBloc({required this.repository, required this.opBloc, required this.authBloc})
    : super(CarsInitial()) {
    on<CarAdd>(_carAdd);
    on<CarEdit>(_carEdit);
    on<CarDelete>(_carDelete);
    on<CarLoad>(_carLoad);
  }

  void _handleError(Object e, String fallbackMessage) {
    if (e is UserUnauthorized) {
      authBloc.add(SessionExpiredEvent());
    } else {
      opBloc.add(FailOperation(message: fallbackMessage));
    }
  }

  Future<void> _carLoad(CarLoad event, Emitter<CarsState> emit) async {
    // Skip the API call if cars are already loaded and no force-refresh requested.
    if (state is CarsLoaded && !event.force) return;

    try {
      emit(CarsLoading());
      List<Car> cars = await repository.getAll(event.teamId);
      emit(CarsLoaded(cars: cars, teamId: event.teamId));
    } catch (e) {
      if (e is UserUnauthorized) {
        authBloc.add(SessionExpiredEvent());
        return;
      }
      emit(CarsLoadingFailed());
    }
  }

  Future<void> _carAdd(CarAdd event, Emitter<CarsState> emit) async {
    final currentState = state;

    opBloc.add(StartOperation());
    try {
      Car newCar = await repository.add(event.teamId, event.plate);

      if (currentState is CarsLoaded) {
        emit(
          currentState.copyWith(
            cars: List<Car>.from(currentState.cars)..add(newCar),
          ),
        );
      }

      opBloc.add(FinishOperation(message: "Auto erfolgreich hinzugefügt"));
    } catch (e) {
      _handleError(e, "Fehler beim Hinzufügen eines Autos");
    }
  }

  Future<void> _carEdit(CarEdit event, Emitter<CarsState> emit) async {
    final currentState = state;

    opBloc.add(StartOperation());
    try {
      await repository.edit(event.teamId, event.newCar);

      if (currentState is CarsLoaded) {
        emit(
          currentState.copyWith(
            cars:
                List<Car>.from(currentState.cars).map((car) {
                  if (car.id == event.newCar.id) {
                    return event.newCar;
                  }

                  return car;
                }).toList(),
          ),
        );
      }

      opBloc.add(FinishOperation(message: "Auto erfolgreich editiert"));
    } catch (e) {
      _handleError(e, "Fehler beim Editieren des Autos");
    }
  }

  Future<void> _carDelete(CarDelete event, Emitter<CarsState> emit) async {
    final currentState = state;

    opBloc.add(StartOperation());
    try {
      await repository.delete(event.carId, event.teamId);

      if (currentState is CarsLoaded) {
        emit(
          CarsLoaded(
            cars: [
              ...currentState.cars.where(
                (car) => car.id != int.parse(event.carId),
              ),
            ],
            teamId: currentState.teamId,
          ),
        );
      }

      opBloc.add(FinishOperation(message: "Auto erfolgreich gelöscht"));
    } catch (e) {
      _handleError(e, "Fehler beim Löschen des Autos");
    }
  }
}
