import 'dart:async'; // Add this import
import 'package:get/get.dart' hide Response;
import 'package:intl/intl.dart';
import 'package:dio/dio.dart' as Response;
import 'package:rounded_loading_button_plus/rounded_loading_button.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../Data/Repository/Admintoken/Getadmintokenrepository.dart';
import '../../../Data/Repository/Notification/Notificationrepository.dart';
import '../../../Data/Repository/Orders/Orderrepository.dart';
import '../../../Data/Repository/Summary/ordersrepository.dart';
import '../../../Helper/Constants/Apiconstants.dart';
import '../../../Helper/Logger.dart';
import '../../../Model/Request/Notification/Notification_request_rider.dart';
import '../../../Model/Request/Notification/Notificationrequest.dart';
import '../../../Model/Request/Orders/Cancelorderrequest.dart';
import '../../../Model/Response/Admintoken/Admintokenresponse.dart';
import '../../../Model/Response/Notification/Notificationresponse.dart';
import '../../../Model/Response/Orders/Getorderresponse.dart';
import '../../../Model/Response/Summary/Cancelorderresponse.dart';
import '../../../View/Home/Homeview.dart';

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

  // Separate lists for each tab
  RxList<OrderDetails> placedOrders = <OrderDetails>[].obs;
  RxList<OrderDetails> ongoingOrders = <OrderDetails>[].obs;
  RxList<OrderDetails> completedOrders = <OrderDetails>[].obs;
  RxList<OrderDetails> cancelledOrders = <OrderDetails>[].obs;

  // Loading states
  RxBool loadingPlaced = false.obs;
  RxBool loadingOngoing = false.obs;
  RxBool loadingCompleted = false.obs;
  RxBool loadingCancelled = false.obs;

  // Track first load per tab
  bool hasLoadedPlaced = false;
  bool hasLoadedOngoing = false;
  bool hasLoadedCompleted = false;
  bool hasLoadedCancelled = false;

  DateTime? now;
  int? userId;
  var orderId;
  var orderHeaderId;

  List<Applocationadmins> adminDetails = [];
  List<String> adminToken = [];

  OrdersRepository ordersRepository = OrdersRepository();
  OrderSummaryRepository orderSummaryRepository = OrderSummaryRepository();
  NotificationRepository notificationRepository = NotificationRepository();
  GetAdminTokenRepository getAdminTokenRepository = GetAdminTokenRepository();

  final RoundedLoadingButtonController cancelOrderButton = RoundedLoadingButtonController();
  final RoundedLoadingButtonController acceptOrderButton = RoundedLoadingButtonController();

  // Timer for auto-refreshing 'created' tab
  Timer? _autoRefreshTimer;

  getAdminToken() async {
    GetAdminToken? result = await getAdminTokenRepository.getAdminToken();
    if (result?.status == true) {
      adminDetails = result?.details?.applocationadmins ?? [];
      adminToken.clear();
      for (var adminDetail in adminDetails) {
        adminToken.add(adminDetail.userfcmtokem ?? '');
      }
    }
    logger.i('adminToken $adminToken');
  }

  // Get orders list by status
  List<OrderDetails> getOrdersByStatus(String status) {
    switch (status) {
      case 'created':
        return placedOrders;
      case 'ongoing':
        return ongoingOrders;
      case 'delivered':
        return completedOrders;
      case 'cancelled':
        return cancelledOrders;
      default:
        return placedOrders;
    }
  }

  // Get loading state by status
  RxBool getLoadingByStatus(String status) {
    switch (status) {
      case 'created':
        return loadingPlaced;
      case 'ongoing':
        return loadingOngoing;
      case 'delivered':
        return loadingCompleted;
      case 'cancelled':
        return loadingCancelled;
      default:
        return loadingPlaced;
    }
  }

  // Check if already loaded
  bool hasLoaded(String status) {
    switch (status) {
      case 'created': return hasLoadedPlaced;
      case 'ongoing': return hasLoadedOngoing;
      case 'delivered': return hasLoadedCompleted;
      case 'cancelled': return hasLoadedCancelled;
      default: return false;
    }
  }

  // Mark as loaded
  void markAsLoaded(String status) {
    switch (status) {
      case 'created': hasLoadedPlaced = true; break;
      case 'ongoing': hasLoadedOngoing = true; break;
      case 'delivered': hasLoadedCompleted = true; break;
      case 'cancelled': hasLoadedCancelled = true; break;
    }
  }

  // Fetch orders for a specific status
  Future<void> getOrder(String status) async {
    final loadingObs = getLoadingByStatus(status);
    final ordersList = getOrdersByStatus(status);

    // Show shimmer only on first load
    if (!hasLoaded(status)) {
      loadingObs.value = true;
    }

    try {
      GetOrders? result = await ordersRepository.getOrders(status);
      ordersList.assignAll(result?.details ?? []);
      markAsLoaded(status);
    } catch (e) {
      logger.e("Error fetching $status orders: $e");
    } finally {
      loadingObs.value = false;
      update();
    }
  }




  // Start auto-refresh for 'created' tab only
  void startAutoRefresh() {
    _autoRefreshTimer?.cancel(); // Cancel any existing
    _autoRefreshTimer = Timer.periodic(Duration(seconds: 3), (timer) {
      // Only refresh 'created' tab
      getOrder('created');
    });
  }

  // Stop auto-refresh
  void stopAutoRefresh() {
    _autoRefreshTimer?.cancel();
    _autoRefreshTimer = null;
  }

  /// Decline Order in created State
  declineOrder(orderheaderId, orderId, customerToken, riderToken) async {
    now = DateTime.now();
    currentTime = DateFormat("yyyy-MM-dd HH:mm:ss").format(
        DateFormat("yyyy-MM-dd HH:mm:ss", "en_US").parse(now.toString()));
    declineOrderResult(
        CancelOrderRequest(
          orderheaderid: orderheaderId,
          orderstatus: "cancelled",
          cancelled: currentTime,
        ),
        orderId,
        customerToken,
        riderToken
    );
  }

  declineOrderResult(CancelOrderRequest data, orderId, customerToken, RiderToken) async {
    CancelOrderResponse? result = await orderSummaryRepository.updateOrders(data);
    logger.i('Update Order Result ${result!.toString()}');
    cancelOrderButton.reset();
    Get.to(() => HomeView(selectedIndex: 0));
    cancelOrderNotification(orderId, customerToken, RiderToken);
  }

  cancelOrderNotification(orderId, customerToken, riderToken) async {
    logger.i('CustomerToken : ${customerToken}');
    logger.i('RiderToken : ${riderToken}');

    SharedPreferences prefs = await SharedPreferences.getInstance();
    String tenantName = prefs.getString('tenantName') ?? '';
    now = DateTime.now();
    notificationDate = DateFormat("yyyy-MM-dd HH:mm:ss").format(
        DateFormat("yyyy-MM-dd HH:mm:ss", "en_US").parse(now.toString()));
    cancelCustomerOrderNotificationResult(
        RiderNotificationRequest(
          notification: NotificationRider(
            title: "Nearle Daily",
            image: "",
            body: "Your Order ${orderId} has been cancelled\nby ${tenantName} ",
            sound: "ring",
          ),
          token: customerToken,
        )
    );

    if (riderToken != '')
      cancelCustomerOrderNotificationResult(
          RiderNotificationRequest(
            notification: NotificationRider(
              title: "NearleXpress",
              image: "",
              body: "${orderId} order has been cancelled\nby ${tenantName} ",
              sound: "ring",
            ),
            token: riderToken,
          )
      );
  }

  cancelCustomerOrderNotificationResult(RiderNotificationRequest data) async {
    NotificationResponse? result = await notificationRepository.notifyRider(data);
    if (result?.status == true) {
      // Handle success if needed
    }
  }

  cancelRiderOrderNotificationResult(RiderNotificationRequest data) async {
    NotificationResponse? result = await notificationRepository.notifyRider(data);
    if (result?.status == true) {
      // Handle success if needed
    }
  }

  @override
  void onInit() {
    super.onInit();
    // Start auto-refresh when controller is initialized
    startAutoRefresh();
  }

  @override
  void onClose() {
    // Stop timer when controller is disposed
    stopAutoRefresh();
    super.onClose();
  }
}