import 'dart:async';

import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/tasks/data/task_repository.dart';
import 'package:flux/features/tasks/models/task_model.dart';
import 'package:flux/features/tasks/models/task_status.dart';
import 'package:get_it/get_it.dart';

part 'dashboard_task_list_state.dart';

class DashboardTaskListCubit extends Cubit<DashboardTaskListState> {
  final TasksRepository _repository = GetIt.I.get<TasksRepository>();
  final String? staffId;
  final String? companyId;
  StreamSubscription<void>? _tasksSubscription;

  DashboardTaskListCubit({required this.staffId, required this.companyId})
    : super(const DashboardTaskListState());

  void startListening() {
    stopListening();

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

    // Primo caricamento
    _loadTasksSilently();

    // Inizio ascolto campanello
    try {
      _tasksSubscription = _repository.watchCompanyTasks(companyId!).listen((
        _,
      ) {
        // Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
        _loadTasksSilently();
      });
    } on Exception catch (e) {
      debugPrint(e.toString());
    }
  }

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

  Future<void> _loadTasksSilently() async {
    try {
      final tasks = await _repository.getTasks(
        companyId: companyId!,
        staffId: staffId,
        statuses: [TaskStatus.open, TaskStatus.inProgress],
        limit: 10,
      );
      if (isClosed) return;
      emit(
        state.copyWith(
          status: DashboardTaskListStatus.success,
          tasks: tasks,
          errorMessage: null,
        ),
      );
    } catch (e) {
      if (isClosed) return;
      emit(
        state.copyWith(
          status: DashboardTaskListStatus.failure,
          errorMessage: e.toString(),
        ),
      );
    }
  }

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