import 'dart:async';

import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/notes/data/notes_repository.dart';
import 'package:flux/features/notes/models/note_model.dart';
import 'package:get_it/get_it.dart';

part 'dashboard_note_list_state.dart';

class DashboardNoteListCubit extends Cubit<DashboardNoteListState> {
  final NotesRepository _repository = GetIt.I.get<NotesRepository>();
  final String? companyId;
  final String? staffId;
  StreamSubscription<void>? _subscription;

  DashboardNoteListCubit({required this.companyId, required this.staffId})
    : super(DashboardNoteListState(status: DashboardNoteListStatus.initial));

  void stopListening() {
    _subscription?.cancel();
    _subscription = null;
  }

  void startListening() {
    stopListening();

    emit(state.copyWith(status: DashboardNoteListStatus.loading));

    // Primo caricamento
    _loadNotesSilently();

    // Inizio ascolto campanello
    try {
      _subscription = _repository
          .notesStream(companyId: companyId!, currentStaffId: staffId!)
          .listen((_) {
            // Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
            _loadNotesSilently();
          });
    } on Exception catch (e) {
      debugPrint(e.toString());
    }
  }

  Future<void> _loadNotesSilently() async {
    try {
      final notes = await _repository.getNotes();
      if (isClosed) return;
      emit(
        state.copyWith(
          status: DashboardNoteListStatus.success,
          notes: notes,
          errorMessage: null,
        ),
      );
    } catch (e) {
      if (isClosed) return;
      emit(
        state.copyWith(
          status: DashboardNoteListStatus.failure,
          errorMessage: e.toString(),
        ),
      );
    }
  }

  @override
  Future<void> close() {
    stopListening();
    return super.close();
  }
}
