import 'dart:async';

import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/tickets/data/ticket_repository.dart';
import 'package:flux/features/tickets/models/ticket_model.dart';
import 'package:get_it/get_it.dart';

part 'dashboard_store_ticket_list_state.dart';

class DashboardStoreTicketListCubit
    extends Cubit<DashboardStoreTicketListState> {
  final TicketRepository _repository = GetIt.I.get<TicketRepository>();
  final String? companyId;
  final String? storeId;
  StreamSubscription<void>? _subscription;

  DashboardStoreTicketListCubit({
    required this.companyId,
    required this.storeId,
  }) : super(
         const DashboardStoreTicketListState(
           status: DashboardStoreTicketListStatus.initial,
         ),
       );

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

  void startListening() {
    stopListening();

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

    // Primo caricamento
    _loadTicketsSilently();

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

  Future<void> _loadTicketsSilently() async {
    try {
      final tickets = await _repository.fetchTickets(
        companyId: companyId!,
        storeId: storeId,
        limit: 10,
        offset: 0,
      );
      if (isClosed) return;
      emit(
        state.copyWith(
          status: DashboardStoreTicketListStatus.success,
          tickets: tickets,
          errorMessage: null,
        ),
      );
    } catch (e) {
      if (isClosed) return;
      emit(
        state.copyWith(
          status: DashboardStoreTicketListStatus.failure,
          errorMessage: e.toString(),
        ),
      );
    }
  }

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