import 'package:cheminova/models/rejected_applicaton_response.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../services/api_client.dart';
import '../services/api_urls.dart';

// Provider class responsible for managing rejected applications data and API calls
class RejectedProvider extends ChangeNotifier {
  // Constructor to automatically fetch rejected applications when the provider is created
  RejectedProvider() {
    getRejectedApplication(); // Fetch rejected applications
  }

  final _apiClient = ApiClient(); // API client instance for making HTTP requests
  RejectedApplicationResponse? rejectedApplicationResponse; // Response object for rejected applications
  List<RejectedApplicationResponse> rejectedApplicationList = []; // List to store rejected applications

  bool _isLoading = false; // Flag to track loading state
  bool get isLoading => _isLoading; // Getter for the loading state

  // Function to update loading state and notify listeners to rebuild UI
  void setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners(); // Notify listeners that the loading state has changed
  }

  // Fetch rejected applications from the API
  Future<void> getRejectedApplication() async {
    setLoading(true); // Set loading state to true while fetching data
    try {
      // Send GET request to the API to fetch rejected applications
      Response response = await _apiClient.get(ApiUrls.rejectedApplication);
      setLoading(false); // Set loading state to false after getting a response

      // If the response is successful (status code 200), parse the data
      if (response.statusCode == 200) {
        // Map each item in the response data to a RejectedApplicationResponse object
        rejectedApplicationList = (response.data as List)
            .map((e) => RejectedApplicationResponse.fromJson(e))
            .toList();
        notifyListeners(); // Notify listeners to update the UI with the new data
      }
    } catch (e) {
      setLoading(false); // In case of error, set loading state to false
    }
  }
}
