import 'package:cheminova/constants/constant.dart';
import 'package:cheminova/models/get_pd_rd_response.dart';
import 'package:cheminova/screens/Add_products_screen.dart';
import 'package:cheminova/services/api_client.dart';
import 'package:cheminova/services/api_urls.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

// Provider class to manage the Principal Distributor (PD) and Retailer Distributor (RD) data
class PdRdProvider extends ChangeNotifier {
  String?
      selectedDistributorType; // Holds the selected distributor type (PD or RD)

  bool _isLoading =
      false; // Flag to indicate whether data is currently being loaded

  bool get isLoading => _isLoading; // Getter for loading state

  List<GetPdRdResponse> _pdRdList = []; // List to store fetched PD/RD data

  List<GetPdRdResponse> get pdRdList =>
      _pdRdList; // Getter to access the PD/RD list

  GetPdRdResponse? selectedPdRd; // Holds the currently selected PD/RD

  final _apiClient =
      ApiClient(); // Instance of the API client to make network requests

  // Method to update the loading state and notify listeners
  void setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners(); // Notify listeners to update the UI
  }

  // Method to fetch PD/RD data from the API based on the selected distributor type
  Future<void> getPdRd() async {
    setLoading(true); // Show loading indicator while data is being fetched
    try {
      // Make GET request to fetch PD/RD data, replacing spaces in the selected distributor type
      Response response = await _apiClient.get(
          ApiUrls.getPdRdUrl + selectedDistributorType!.replaceAll(' ', ''));

      setLoading(false); // Hide loading indicator after response

      if (response.statusCode == 200) {
        // If response is successful, parse the data into a list of GetPdRdResponse objects
        _pdRdList = (response.data as List)
            .map((json) => GetPdRdResponse.fromJson(json))
            .toList();
        notifyListeners(); // Notify listeners to refresh the UI with new data
      } else {
        // Log an error message if the response is not successful
        debugPrint("Failed to load data: ${response.statusCode}");
      }
    } catch (e) {
      // Log any exceptions that occur during the API call
      debugPrint("Error occurred: $e");
    } finally {
      // Always hide the loading indicator once the operation completes
      setLoading(false);
    }
  }

  // Method to update the selected distributor type and fetch corresponding PD/RD data
  void updateDistributorType(String? val) {
    selectedDistributorType = val; // Update selected distributor type
    selectedPdRd = null; // Reset the selected PD/RD
    notifyListeners(); // Notify listeners to update the UI
    getPdRd(); // Fetch the PD/RD data for the selected distributor type
  }

  // Method to update the selected PD/RD and navigate to the Add Products screen
  updatePdRdValue(GetPdRdResponse? val) {
    selectedPdRd = val; // Update selected PD/RD
    notifyListeners(); // Notify listeners to update the UI

    // Delay navigation slightly to ensure smooth transition
    Future.delayed(const Duration(milliseconds: 500), () {
      if (selectedPdRd != null && selectedDistributorType != null) {
        // Navigate to the AddProductsScreen, passing selected distributor type and PD/RD details
        Navigator.push(
            navigatorKey.currentContext!,
            MaterialPageRoute(
                builder: (context) => AddProductsScreen(
                    distributorType: selectedDistributorType!,
                    tradeName: selectedPdRd!.name ?? '',
                    pdRdId: selectedPdRd!.sId!)));
      }
    });
  }
}
