import 'dart:convert';
import 'package:cheminova/constants/constant.dart';
import 'package:cheminova/screens/data_submit_successfull.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';
import '../models/products_response.dart';

// Provider class responsible for handling product data and API requests
class ProductProvider extends ChangeNotifier {
  final _apiClient = ApiClient(); // API client for making HTTP requests
  ProductResponse? productResponse; // Response object for product list
  List<ProductModel> productList = []; // List of products
  List<ProductModel> searchList = []; // Filtered list of products for search

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

  List<ProductModel> selectedProducts = []; // List of selected products

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

  // Filter products based on the search query (either by product name or SKU)
  void filterProducts(String query) {
    searchList = productList.where((product) {
      final productNameLower = product.productName.toLowerCase();
      final productSkuLower = product.sku.toLowerCase();
      final searchLower = query.toLowerCase();
      return productNameLower.contains(searchLower) ||
          productSkuLower.contains(searchLower);
    }).toList();
    notifyListeners(); // Notify listeners to update UI with search results
  }

  // Fetch the list of products from the API
  // Future<void> getProducts() async {
  //   Response response = await _apiClient.get(ApiUrls.getProducts);
  //   debugPrint('Response: $response');
  //   setLoading(false);
  //   if (response.statusCode == 200) {
  //     productResponse = ProductResponse.fromJson(response.data);
  //     productList = productResponse!.products!
  //         .map((product) => ProductModel(sku: product.sKU!, productName: product.name!,id: product.sId!))
  //         .toList();
  //     notifyListeners(); // Notify listeners to update the UI with the product list
  //   }
  // }



  Future<void> getProducts() async {
    bool moreDataAvailable = true;
    int page = 1;

    while (moreDataAvailable) {
      Response response = await _apiClient.get('${ApiUrls.getProducts}?page=$page');
      debugPrint('Response: $response');
      setLoading(false);

      if (response.statusCode == 200) {
        productResponse = ProductResponse.fromJson(response.data);
        productList.addAll(
          productResponse!.products!.map(
                (product) => ProductModel(
              sku: product.sKU!,
              productName: product.name!,
              id: product.sId!,
            ),
          ).toList(),
        );

        moreDataAvailable = productResponse!.totalPages! > page;
        page++;
        notifyListeners(); // Notify listeners to update the UI with the new product list
      }
    }
  }


  // Submit selected products to the API
  Future<void> submitProducts(
      {required String distributorType, required String pdRdId, String? inventoryId}) async {
    setLoading(true);
    try {
      // Send POST request to submit products
      Response response = await _apiClient.post(ApiUrls.submitProductUrl,
          data: json.encode({

            "addedFor": distributorType.replaceAll(' ', ''),
            "addedForId": pdRdId,
            "products": selectedProducts.map((e) => e.toJson()).toList()
          }));
      setLoading(false);

      // Handle successful response
      if (response.statusCode == 201) {
        ScaffoldMessenger.of(
          navigatorKey.currentContext!,
        ).showSnackBar(
          SnackBar(content: Text(response.data['message'])),
        );

        // Update task if inventoryId is provided
        if (inventoryId != null) {
          _apiClient.put(ApiUrls.updateTaskInventoryUrl + inventoryId, data: null).then((value) {
            debugPrint('Task Updated');
            if (value.statusCode == 200) {
              resetProducts(); // Reset selected products and product list
              Navigator.push(
                  navigatorKey.currentContext!,
                  MaterialPageRoute(
                      builder: (context) => const DataSubmitSuccessFullScreen()));
            } else {
              ScaffoldMessenger.of(
                navigatorKey.currentContext!,
              ).showSnackBar(
                const SnackBar(content: Text('Task not updated')),
              );
            }
          });
        } else {
          resetProducts();
          Navigator.push(
              navigatorKey.currentContext!,
              MaterialPageRoute(
                  builder: (context) => const DataSubmitSuccessFullScreen()));
        }
      }
    } catch (e) {
      setLoading(false);
      debugPrint("Error: $e"); // Handle any errors during the request
    }
  }

  // Reset selected products and product list
  void resetProducts() {
    selectedProducts.clear();
    productList.clear();
    productResponse = null;
    notifyListeners(); // Notify listeners to update the UI
  }
}

// Model class for Product
class ProductModel {
  String id; // ID of the product
  String sku; // SKU of the product
  String productName; // Name of the product
  int? sale; // Sale quantity (optional)
  int? inventory; // Inventory quantity (optional)

  // Constructor for ProductModel
  ProductModel(
      {
        required this.id,
        required this.sku,
        required this.productName,
        this.sale,
        this.inventory});

  // Factory method to create a ProductModel from JSON
  factory ProductModel.fromJson(Map<String, dynamic> json) {
    return ProductModel(
      id:json['_id'],
        sku: json['SKU'],
        productName: json['ProductName'],
        sale: json['Sale'],
        inventory: json['Inventory']);
  }

  get comments => null; // Placeholder for any future comments functionality

  // Convert ProductModel to JSON format for API requests
  Map<String, dynamic> toJson() {
    return {
      '_id': id,
      'SKU': sku,
      'ProductName': productName,
      'Sale': sale,
      'Inventory': inventory
    };
  }
}
