import 'package:client_home/src/domain/repositories/home_repository_interface.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow_domain/krow_domain.dart';
import '../../domain/usecases/get_dashboard_data_usecase.dart';
import '../../domain/usecases/get_recent_reorders_usecase.dart';
import '../../domain/usecases/get_user_session_data_usecase.dart';
import 'client_home_event.dart';
import 'client_home_state.dart';

/// BLoC responsible for managing the state and business logic of the client home dashboard.
class ClientHomeBloc extends Bloc<ClientHomeEvent, ClientHomeState> {
  final GetDashboardDataUseCase _getDashboardDataUseCase;
  final GetRecentReordersUseCase _getRecentReordersUseCase;
  final GetUserSessionDataUseCase _getUserSessionDataUseCase;

  ClientHomeBloc({
    required GetDashboardDataUseCase getDashboardDataUseCase,
    required GetRecentReordersUseCase getRecentReordersUseCase,
    required GetUserSessionDataUseCase getUserSessionDataUseCase,
  }) : _getDashboardDataUseCase = getDashboardDataUseCase,
       _getRecentReordersUseCase = getRecentReordersUseCase,
       _getUserSessionDataUseCase = getUserSessionDataUseCase,
       super(const ClientHomeState()) {
    on<ClientHomeStarted>(_onStarted);
    on<ClientHomeEditModeToggled>(_onEditModeToggled);
    on<ClientHomeWidgetVisibilityToggled>(_onWidgetVisibilityToggled);
    on<ClientHomeWidgetReordered>(_onWidgetReordered);
    on<ClientHomeLayoutReset>(_onLayoutReset);

    add(ClientHomeStarted());
  }

  Future<void> _onStarted(
    ClientHomeStarted event,
    Emitter<ClientHomeState> emit,
  ) async {
    emit(state.copyWith(status: ClientHomeStatus.loading));
    try {
      // Get session data
      final UserSessionData sessionData = _getUserSessionDataUseCase();

      // Get dashboard data
      final HomeDashboardData data = await _getDashboardDataUseCase();
      final List<ReorderItem> reorderItems = await _getRecentReordersUseCase();

      emit(
        state.copyWith(
          status: ClientHomeStatus.success,
          dashboardData: data,
          reorderItems: reorderItems,
          businessName: sessionData.businessName,
          photoUrl: sessionData.photoUrl,
        ),
      );
    } catch (e) {
      emit(
        state.copyWith(
          status: ClientHomeStatus.error,
          errorMessage: e.toString(),
        ),
      );
    }
  }

  void _onEditModeToggled(
    ClientHomeEditModeToggled event,
    Emitter<ClientHomeState> emit,
  ) {
    emit(state.copyWith(isEditMode: !state.isEditMode));
  }

  void _onWidgetVisibilityToggled(
    ClientHomeWidgetVisibilityToggled event,
    Emitter<ClientHomeState> emit,
  ) {
    final Map<String, bool> newVisibility = Map<String, bool>.from(state.widgetVisibility);
    newVisibility[event.widgetId] = !(newVisibility[event.widgetId] ?? true);
    emit(state.copyWith(widgetVisibility: newVisibility));
  }

  void _onWidgetReordered(
    ClientHomeWidgetReordered event,
    Emitter<ClientHomeState> emit,
  ) {
    final List<String> newList = List<String>.from(state.widgetOrder);
    int oldIndex = event.oldIndex;
    int newIndex = event.newIndex;

    if (oldIndex < newIndex) {
      newIndex -= 1;
    }
    final String item = newList.removeAt(oldIndex);
    newList.insert(newIndex, item);

    emit(state.copyWith(widgetOrder: newList));
  }

  void _onLayoutReset(
    ClientHomeLayoutReset event,
    Emitter<ClientHomeState> emit,
  ) {
    emit(
      state.copyWith(
        widgetOrder: const <String>[
          'actions',
          'reorder',
          'coverage',
          'spending',
          'liveActivity',
        ],
        widgetVisibility: const <String, bool>{
          'actions': true,
          'reorder': true,
          'coverage': true,
          'spending': true,
          'liveActivity': true,
        },
      ),
    );
  }
}
