import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:get/get.dart' hide Response;
import '../../../Data/Repository/Summary/ordersrepository.dart';
import '../../../Model/Response/Summary/Getsummarysresponse.dart';

class TodayOrderController extends GetxController {
  String? currentTime;
  String? notificationDate;

  RxBool shimmer = true.obs;
  bool filter2 = false;
  bool searchMode = false;
  bool showOrder = false;

  List<DeliveriesDetails> orderAllList = [];
  List<DeliveriesDetails> searchCompare = [];

  var orderId;
  var orderHeaderId;
  var userId;

  OrderSummaryRepository orderSummaryRepository = OrderSummaryRepository();
  TextEditingController searchController = TextEditingController();

  Timer? _timer; // To hold the periodic timer

  @override
  void onInit() {
    super.onInit();
    getOrders(); // Initial call
    startAutoRefresh(); // Start periodic refresh
  }

  void startAutoRefresh() {
    _timer = Timer.periodic(const Duration(seconds: 3), (timer) {
      getOrders(); // Refresh every 3 seconds
    });
  }

  getOrders() async {
    try {
      GetDeliveries? result = await orderSummaryRepository.getOrdersToday();
      if (result != null) {
        todayOrderResult(result);
        print('printresultjson${result.toJson()}');
      }
    } catch (e) {
      print("Error fetching orders: $e");
      // Optionally handle error (e.g., show snackbar)
    }
  }

  todayOrderResult(GetDeliveries orderData) async {
    print('todayorderresultss');
    orderAllList.clear();
    if (orderData.details != null) {
      print('dataDetailsif${orderData.details}');
      searchCompare.clear();
      searchCompare.addAll(orderData.details!);
      orderAllList.addAll(orderData.details!);
      print('orderalllistlengthincontroller ${orderAllList.length}');
    }

    showOrder = orderAllList.any((order) => order.orderstatus != 'created');
    print('showOrder: $showOrder');

    shimmer.value = false;
    update();
  }

  search(String searchData) {
    print("datasearchData$searchData");
    print("lenght${orderAllList.length}");

    // Restore from searchCompare before filtering
    orderAllList = List.from(searchCompare);

    if (searchData.isEmpty) {
      searchMode = false;
      update();
      return;
    }

    List<DeliveriesDetails> searchResults = searchCompare
        .where((value) =>
        value.pickupcontactno!
            .toLowerCase()
            .contains(searchData.toLowerCase()))
        .toList();

    orderAllList = searchResults;
    searchMode = true;
    update();
  }

  @override
  void onClose() {
    _timer?.cancel(); // Cancel timer to prevent memory leaks
    searchController.dispose();
    super.onClose();
  }
}