import 'dart:async';

import 'package:flutter/material.dart';
import 'package:initial_folder/models/qna_model.dart';
import 'package:initial_folder/services/qna_service.dart';
import 'package:rxdart/rxdart.dart';

enum DataState { loading, noData, hasData, error }
enum ResultStateLike { loading, error }

class ReplyQnaProvider with ChangeNotifier {
  final _service = QnaService();
  StreamController<QnaModel> streamController = BehaviorSubject();
  String _message = '';
  String get message => _message;
  DataState? _state;
  DataState? get state => _state;
  QnaModel? _qnaModel;
  QnaModel? get result => _qnaModel;

  set qnaModel(QnaModel? qnaModel) {
    _qnaModel = qnaModel;
    notifyListeners();
  }

  Stream<QnaModel> get replyQnaStream {
    return streamController.stream;
  }

  Future<void> getReplyQna(String idCourse, int index) async {
    QnaModel qnaModel = await _service.getMyQna(idCourse);
    streamController.add(qnaModel);
  }

  Future<void> getReplyQnaById(String idCourse, String idQna) async {
    try {
      _state = DataState.loading;
      QnaModel qnaModel = await _service.getMyQna(idCourse);

      // Filter untuk mencari item dengan idQna yang sesuai dalam List<List<QnaDataModel>>
      var filteredQna = qnaModel.data.expand((innerList) => innerList)
          .where((qna) => qna.idQna == idQna).toList();

      if (filteredQna.isNotEmpty) {
        // Set data yang sudah terfilter ke dalam streamController
        streamController.add(QnaModel(data: [filteredQna]));
        _state = DataState.hasData;
      } else {
        // Jika tidak ada data, set status noData
        _state = DataState.noData;
      }
    } catch (e) {
      _state = DataState.error;
      _message = "Terjadi kesalahan saat mengambil data balasan.";
      streamController.addError(_message);
    }
    notifyListeners();
  }

  @override
  void dispose() {
    streamController.close();  
    super.dispose();
  }
}
