import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:krow_core/core.dart';
import 'package:krow_domain/krow_domain.dart';

import 'package:staff_home/src/domain/usecases/get_home_shifts.dart';
import 'package:staff_home/src/domain/repositories/home_repository.dart';

part 'home_state.dart';

/// Simple Cubit to manage home page state (shifts + loading/error).
class HomeCubit extends Cubit<HomeState> with BlocErrorHandler<HomeState> {
  final GetHomeShifts _getHomeShifts;
  final HomeRepository _repository;

  HomeCubit(HomeRepository repository)
    : _getHomeShifts = GetHomeShifts(repository),
      _repository = repository,
      super(const HomeState.initial());

  Future<void> loadShifts() async {
    if (isClosed) return;
    emit(state.copyWith(status: HomeStatus.loading));
    await handleError(
      emit: emit,
      action: () async {
        final result = await _getHomeShifts.call();
        final name = await _repository.getStaffName();
        if (isClosed) return;
        emit(
          state.copyWith(
            status: HomeStatus.loaded,
            todayShifts: result.today,
            tomorrowShifts: result.tomorrow,
            recommendedShifts: result.recommended,
            staffName: name,
            // Mock profile status for now, ideally fetched from a user repository
            isProfileComplete: false,
          ),
        );
      },
      onError: (String errorKey) {
        if (isClosed) return state; // Avoid state emission if closed, though emit handles it gracefully usually
        return state.copyWith(status: HomeStatus.error, errorMessage: errorKey);
      },
    );
  }


  void toggleAutoMatch(bool enabled) {
    emit(state.copyWith(autoMatchEnabled: enabled));
  }
}
