import 'dart:developer';

import 'package:cheminova/controller/get_single_placed_order_service.dart';
import 'package:cheminova/controller/place_order_controller.dart';
import 'package:cheminova/models/place_order_list_model.dart';
import 'package:cheminova/services/api_service.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../models/product_model1.dart';
import 'get_place_order_service.dart';

class GetPlacedOrderController extends GetxController {
  final ApiService _apiService = ApiService();
  final GetOrderPlacedService _getOrderPlacedService = GetOrderPlacedService();
  final OrderPlacedController _orderPlacedController =
      Get.put(OrderPlacedController());
  final GetSingleOrderPlacedService _getSingleOrderPlacedService =
      GetSingleOrderPlacedService();
  List<PlacedOrderList> placedOrders = <PlacedOrderList>[].obs;
  List<PlacedOrderList> filterOrder = <PlacedOrderList>[].obs;
  var products = <Product>[].obs;

  var isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    getOrders(); // Fetch the orders immediately on initialization
  }

  RxInt currentPage = 1.obs;
  RxBool hasMoreOrders = true.obs;

  RxString productStatus = 'All'.obs;

  Future<void> getOrders() async {
    if (isLoading.value || !hasMoreOrders.value) return;

    isLoading.value = true;

    try {
      final response = await _apiService
          .get('/api/rd-place-order?page=${currentPage.value}');
      log('response ---- $response');
      PlacedOrderResponse data = PlacedOrderResponse.fromJson(response.data);

      if (response.statusCode == 200) {
        placedOrders.addAll(data.placedOrders ?? []);
        currentPage++;
        hasMoreOrders.value = placedOrders.length < data.totalOrders!.toInt();
      } else {
        throw Exception('Failed to load orders');
      }
    } catch (e) {

      debugPrint('Error fetching orders: $e');
    } finally {
      isLoading.value = false;
    }
  }

  void resetPagination() {
    placedOrders.clear();
    currentPage.value = 1;
    hasMoreOrders.value = true;
  }

  Future<void> searchOrder() async {
    try {
      isLoading.value = true;
      final order = await _getSingleOrderPlacedService
          .getSinglePlacedOrder(placedOrders[0].sId ?? '');
      if (order != null) {
        placedOrders.clear(); // Clear existing orders if needed
        placedOrders.add(order);
      } else {
        // Handle order not found case
      }
    } catch (e) {
      // Handle exceptions
    } finally {
      isLoading.value = false;
    }
  }

  void updateProductStatus(dynamic newValue) {
    productStatus.value = newValue;
    filterOrder.clear();
    if (productStatus.value == 'All') {
      filterOrder.addAll(placedOrders);
    } else {
      filterOrder.addAll(placedOrders
          .where((order) => order.status.toString().toLowerCase() == productStatus.value.toLowerCase())
          .toList());
    }
  }

// // Optional: Reset the pagination if needed
// void resetPagination() {
//   _getOrderPlacedService.resetPagination();
//   placedOrders.clear(); // Clear existing data
//   getOrders(); // Fetch fresh data
// }
}
