import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../Data/Repository/Summary/ordersrepository.dart';
import '../../Helper/Logger.dart';
import '../../Model/Response/Summary/Getsummarysresponse.dart';
import '../../Model/Response/Summary/Ordersummaryresponse.dart';

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

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

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

  var orderId;
  var orderHeaderId;
  var userId;

  OrderSummaryRepository orderSummaryRepository = OrderSummaryRepository();

  TextEditingController searchController = TextEditingController();

  late OrderSummaryDetails orderSummaryDetails;

  RxInt currentTabIndex = 0.obs;

  RxBool isOrdersLoading = false.obs;

  bool hasLoadedOrdersOnce = false;

  Future<void> getOrders(String period) async {
    if (!hasLoadedOrdersOnce) {
      isOrdersLoading.value = true; // Show loader only on first call
    }

    try {
      GetDeliveries? result;

      switch (period) {
        case 'today':
          result = await orderSummaryRepository.getOrdersToday();
          break;
        case 'week':
          result = await orderSummaryRepository.getOrdersWeek();
          break;
        case 'month':
          result = await orderSummaryRepository.getOrdersMonth();
          break;
        default:
          isOrdersLoading.value = false;
          return;
      }

      if (result != null) {
        await processOrderResult(result);
        logger.i('Result Json : ${result.toJson()}');
      }
    } catch (e) {
      print("Error fetching orders: $e");
    } finally {
      isOrdersLoading.value = false;
      hasLoadedOrdersOnce = true; // Set the flag after first successful call
    }
  }



  Future<void> search(String keyword) async {
    if (keyword.isEmpty) {
      searchMode.value = false;
      searchOrderList.clear();
      update();
      return;
    }

    searchMode.value = true;
    isOrdersLoading.value = true;

    try {
      GetDeliveries? result;
      switch (currentTabIndex.value) {
        case 0:
          result = await orderSummaryRepository.getOrdersToday(keyword: keyword);
          break;
        case 1:
          result = await orderSummaryRepository.getOrdersWeek(keyword: keyword);
          break;
        case 2:
          result = await orderSummaryRepository.getOrdersMonth(keyword: keyword);
          break;
        default:
          isOrdersLoading.value = false;
          return;
      }

      if (result != null) {
        searchOrderList.clear();
        searchOrderList.addAll(result.details ?? []);
        logger.i('Search Result Json: ${result.toJson()}');
      }
    } catch (e) {
      print("Error searching orders: $e");
    } finally {
      isOrdersLoading.value = false;
      update();
    }
  }


  getSummary() async {
    final result = await orderSummaryRepository.getOrderSummary();
    if(result?.status == true) {
      orderSummaryDetails = result?.details ?? OrderSummaryDetails();
    }
    update();
  }



  Future<void> processOrderResult(GetDeliveries orderData) async {
    logger.i('orderresultss');
    orderAllList.clear();
    if (orderData.details != null) {
      print('dataDetailsif${orderData.details}');
      searchOrderList.clear();
      searchOrderList.addAll(orderData.details!);
      orderAllList.addAll(orderData.details!);
      print('orderalllistlengthincontroller ${orderAllList.length}');
    }
    for (var currentOrdersValue in orderAllList) {
      if (currentOrdersValue.orderstatus != 'created') {
        showOrder = true;
        print('showNoOrderssif $showOrder');
        break;
      } else {
        showOrder = false;
        print('showNoOrder $showOrder');
      }
    }
    shimmer.value = false;
    update();
  }

  // void search(String searchData) {
  //   print("datasearchData$searchData");
  //   print("lenght${orderAllList.length}");
  //   orderAllList.clear();
  //   if (filter2) {
  //     List<DeliveriesDetails> search = searchCompare
  //         .where((value) =>
  //         value.pickupcontactno!
  //             .toLowerCase()
  //             .contains(searchController.text.toLowerCase()))
  //         .toList();
  //     orderAllList = search;
  //   } else {
  //     List<DeliveriesDetails> search = searchCompare
  //         .where((value) =>
  //         value.pickupcontactno!
  //             .toLowerCase()
  //             .contains(searchController.text.toLowerCase()))
  //         .toList();
  //     orderAllList = search;
  //   }
  //   searchMode = true;
  //   update();
  // }

  @override
  void onInit() {
    super.onInit();
    orderSummaryDetails = OrderSummaryDetails();
  }
}