import 'package:english_learning/core/services/repositories/history_repository.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:english_learning/features/learning/provider/section_provider.dart';
import 'package:flutter/material.dart';
import 'package:english_learning/features/history/models/history_model.dart';

class HistoryProvider with ChangeNotifier {
  final HistoryRepository _repository;
  final SectionProvider _sectionProvider;
  List<LearningHistory> _learningHistory = [];
  int _selectedPageIndex = 0;
  bool _isLoading = false;
  String? _error;
  bool _isInitialized = false;

  HistoryProvider(
    this._repository,
    this._sectionProvider,
  );

  List<LearningHistory> get learningHistory => _learningHistory;
  int get selectedPageIndex => _selectedPageIndex;
  bool get isLoading => _isLoading;
  String? get error => _error;
  bool get isInitialized => _isInitialized;

  Future<void> loadInitialData(String token) async {
    if (_isInitialized) return; // Prevent double initialization

    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      // Only fetch sections if they haven't been fetched yet
      if (_sectionProvider.sections.isEmpty) {
        await _sectionProvider.fetchSections(token);
      }

      if (_sectionProvider.sections.isEmpty) {
        _error = 'No sections available';
        return;
      }

      // Get the first section's ID
      String firstSectionId = _sectionProvider.sections.first.id;

      // Fetch history for the first section
      _learningHistory =
          await _repository.getLearningHistory(firstSectionId, token);
      _error = null;
      _isInitialized = true; // Mark as initialized
    } catch (e) {
      _error = 'Error loading data: ${e.toString()}';
      _learningHistory = [];
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  void setSelectedPageIndex(int index) {
    _selectedPageIndex = index;
    notifyListeners();
  }

  Future<void> fetchLearningHistory(String token) async {
    if (_sectionProvider.sections.isEmpty) {
      _error = 'No sections available';
      notifyListeners();
      return;
    }

    String sectionId = _sectionProvider.sections[_selectedPageIndex].id;
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      final history = await _repository.getLearningHistory(sectionId, token);
      _learningHistory = history;
      _error = null;
    } catch (e) {
      _error = 'Error fetching learning history: ${e.toString()}';
      _learningHistory = [];
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Color getColorForLevels(
    dynamic currentLevel,
    dynamic nextLevel,
    bool isPass,
  ) {
    if (isPass) {
      return AppColors.greenColor;
    }

    int? current = _parseLevel(currentLevel);
    int? next = _parseLevel(nextLevel);

    if (current == null || next == null) {
      return AppColors.blackColor;
    }

    if (current == next) {
      return AppColors.blackColor;
    } else if (next > current) {
      return AppColors.blueColor;
    } else {
      return AppColors.redColor;
    }
  }

  int? _parseLevel(String? level) {
    if (level == null) return null;
    if (level.toLowerCase() == 'pretest') {
      return 0; // Treat Pretest as level 0
    }
    return int.tryParse(level.replaceAll('Level ', '')) ?? -1;
  }

  Future<void> refreshData(String token) async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      await _sectionProvider.fetchSections(token);
      if (_sectionProvider.sections.isNotEmpty) {
        await fetchLearningHistory(token);
      } else {
        _error = 'No sections available';
      }
    } catch (e) {
      _error = 'Error refreshing data: ${e.toString()}';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> loadHistoryData(String token) async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      await _sectionProvider.fetchSections(token);
      if (_sectionProvider.sections.isNotEmpty) {
        String firstSectionId = _sectionProvider.sections.first.id;
        _learningHistory =
            await _repository.getLearningHistory(firstSectionId, token);
      } else {
        _error = 'No sections available';
      }
    } catch (e) {
      _error = 'Error loading data: ${e.toString()}';
      _learningHistory = []; // Clear the list in case of error
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }
}
