import 'dart:async';

import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/operations/data/operations_repository.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:get_it/get_it.dart';

part 'dashboard_store_operation_list_state.dart';

class DashboardStoreOperationListCubit
    extends Cubit<DashboardStoreOperationListState> {
  final OperationsRepository _repository = GetIt.I.get<OperationsRepository>();
  final String? companyId;
  final String? storeId;
  StreamSubscription<void>? _operationsSubscription;
  DashboardStoreOperationListCubit({
    required this.companyId,
    required this.storeId,
  }) : super(
         const DashboardStoreOperationListState(
           status: DashboardStoreOperationListStatus.initial,
         ),
       );

  void startListening() {
    emit(state.copyWith(status: DashboardStoreOperationListStatus.loading));
    stopListening();

    // Primo caricamento
    _loadOperationsSilently();

    // Inizio ascolto campanello
    try {
      _operationsSubscription = _repository
          .watchStoreOperations(storeId: storeId!, limit: 10)
          .listen((_) {
            // Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
            _loadOperationsSilently();
          });
    } on Exception catch (e) {
      debugPrint(e.toString());
    }
  }

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

  void _loadOperationsSilently() async {
    try {
      final operations = await _repository.fetchOperations(
        companyId: companyId!,
        storeId: storeId!,
        limit: 10,
        offset: 0,
      );
      if (isClosed) return;
      emit(
        state.copyWith(
          status: DashboardStoreOperationListStatus.success,
          operations: operations,
          error: null,
        ),
      );
    } catch (e) {
      if (isClosed) return;
      emit(
        state.copyWith(
          status: DashboardStoreOperationListStatus.failure,
          error: e.toString(),
        ),
      );
    }
  }

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