import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/tracking/data/tracking_repository.dart';
import 'package:flux/features/tracking/models/tracking_model.dart';
import 'package:get_it/get_it.dart';

// Stati base: initial, loading, loaded, error
class TrackingState {
  final bool isLoading;
  final List<TrackingModel> logs;

  TrackingState({this.isLoading = false, this.logs = const []});
}

class TrackingCubit extends Cubit<TrackingState> {
  final TrackingRepository _repo = GetIt.I.get<TrackingRepository>();
  final String companyId = GetIt.I.get<SessionCubit>().state.company!.id!;

  TrackingCubit() : super(TrackingState());

  Future<void> loadTrackings(
    String parentId,
    TrackingParentType parentType,
  ) async {
    emit(TrackingState(isLoading: true, logs: []));
    final trackings = await _repo.getTrackingsByParent(
      parentId: parentId,
      parentType: parentType,
    );
    emit(TrackingState(isLoading: false, logs: trackings));
  }

  Future<void> addTimelineEvent({
    required String parentId,
    required TrackingParentType parentType,
    required String message,
    required bool isInternal,
    String? staffId,
  }) async {
    // Aggiungiamo un feedback visivo immediato (Optimistic UI) se vogliamo,
    // oppure semplicemente mostriamo il loading
    await _repo.logQuickEvent(
      companyId: companyId,
      message: message,
      type: TrackingType.manualNote,
      parentId: parentId,
      parentType: parentType,
      staffId: staffId,
      isInternal: isInternal,
    );
    // Ricarichiamo la lista fresca dal server
    await loadTrackings(parentId, parentType);
  }
}
