import 'package:flutter/material.dart';
import '../../Models/hrmModels/advanceListResponse.dart';
import '../../services/api_calling.dart';

class AdvanceListProvider extends ChangeNotifier {
  bool _isLoading = false;
  bool get isLoading => _isLoading;

  String? _errorMessage;
  String? get errorMessage => _errorMessage;

  List<AdvanceList> _advanceList = [];
  List<AdvanceList> get advanceList => _advanceList;

  int _currentPage = 1;
  int get currentPage => _currentPage;

  bool _hasMore = true;
  bool get hasMore => _hasMore;

  /// Fetch Advance List
  Future<void> fetchAdvanceList(
      BuildContext context, String session, String empId,
      {int page = 1, bool loadMore = false}) async {
    if (_isLoading) return;

    _isLoading = true;
    if (!loadMore) {
      _errorMessage = null;
      _advanceList = [];
      _currentPage = 1;
      _hasMore = true;
    }
    notifyListeners();

    try {
      final response = await ApiCalling.advanceListAPI(session, empId, page);

      debugPrint('lenght: ${response?.advanceList?.length}, empId: ${empId}, session: ${session}, pageNumber: $page');
      if (response != null) {
        if (response.error == "0") {
          final newList = response.advanceList ?? [];

          if (loadMore) {
            _advanceList.addAll(newList);
          } else {
            _advanceList = newList;
          }

          _currentPage = page;
          _hasMore = newList.isNotEmpty;
        } else {
          _errorMessage = response.message ?? "Something went wrong";
        }
      } else {
        _errorMessage = "No response from server";
      }
    } catch (e) {
      _errorMessage = "Failed to fetch advance list: $e";
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// Refresh Advance List
  Future<void> refreshAdvanceList(
      BuildContext context, String session, String empId) async {
    await fetchAdvanceList(context, session, empId, page: 1, loadMore: false);
  }

  /// Load More (Pagination)
  Future<void> loadMoreAdvanceList(
      BuildContext context, String session, String empId) async {
    if (!_hasMore || _isLoading) return;
    await fetchAdvanceList(context, session, empId,
        page: _currentPage + 1, loadMore: true);
  }

  /// Clear state
  void clear() {
    _advanceList = [];
    _errorMessage = null;
    _currentPage = 1;
    _hasMore = true;
    notifyListeners();
  }
}
