import 'dart:async';
import 'package:equatable/equatable.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:get_it/get_it.dart';

part 'task_list_state.dart';

class TaskListCubit extends Cubit<TaskListState> {
  final TasksRepository _repository = GetIt.I.get<TasksRepository>();
  final String currentCompanyId;
  final String? currentStoreId;

  // Il nostro abbonamento allo stream del repository
  StreamSubscription<void>? _taskSubscription;

  TaskListCubit({required this.currentCompanyId, this.currentStoreId})
    : super(const TaskListState()) {
    _initRealtime();
  }

  void _initRealtime() {
    emit(state.copyWith(status: TaskListStatus.loading));

    // Primo caricamento
    _loadTasksSilently();

    // Ci mettiamo in ascolto del campanello del Repository
    _taskSubscription = _repository.watchCompanyTasks(currentCompanyId).listen((
      _,
    ) {
      // Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo!
      _loadTasksSilently();
    });
  }

  Future<void> loadTasks() async {
    emit(state.copyWith(status: TaskListStatus.loading));
    await _loadTasksSilently();
  }

  Future<void> _loadTasksSilently() async {
    try {
      final tasks = await _repository.getTasks(
        companyId: currentCompanyId,
        storeId: currentStoreId,
      );

      emit(
        state.copyWith(
          status: TaskListStatus.success,
          tasks: tasks,
          errorMessage: null,
        ),
      );
    } catch (e) {
      emit(
        state.copyWith(
          status: TaskListStatus.failure,
          errorMessage: e.toString(),
        ),
      );
    }
  }

  @override
  Future<void> close() {
    // Stacchiamo l'abbonamento. Il controller.onCancel nel Repo farà il resto!
    _taskSubscription?.cancel();
    return super.close();
  }
}
