// lib/features/home/providers/completed_topics_provider.dart

// ignore_for_file: unnecessary_null_comparison

import 'package:english_learning/core/services/repositories/completed_topics_repository.dart';
import 'package:english_learning/features/home/models/completed_topics_model.dart';
import 'package:flutter/foundation.dart';

class CompletedTopicsProvider with ChangeNotifier {
  final CompletedTopicsRepository _repository;
  List<CompletedTopic> _completedTopics = [];
  bool _isLoading = false;
  String? _error;

  CompletedTopicsProvider(this._repository);

  List<CompletedTopic> get completedTopics => _completedTopics;
  bool get isLoading => _isLoading;
  String? get error => _error;

  void resetData() {
    _completedTopics = [];
    _isLoading = false;
    _error = null;
    notifyListeners();
  }

  Future<void> fetchCompletedTopics(String token) async {
    resetData();
    _isLoading = true;
    notifyListeners();

    try {
      final result = await _repository.getCompletedTopics(token);

      // Tambahkan pengecekan null secara eksplisit
      if (result == null) {
        _completedTopics = []; // Set ke list kosong
        _error = 'No topics found'; // Beri pesan default
      } else {
        // Pastikan result adalah List
        _completedTopics = result;
        _error = null;
      }
    } catch (e) {
      // Tangani error
      _completedTopics = [];
      _error = e.toString();
    } finally {
      // Selalu set loading ke false
      _isLoading = false;
      notifyListeners();
    }
  }
}
