import 'package:get/get.dart';
import 'package:hallo_doctor_doctor_app/app/models/timeslot_model.dart';
import 'package:hallo_doctor_doctor_app/app/services/timeslot_service.dart';

class OrderController extends GetxController
    with StateMixin<Map<String, List<TimeSlot>>> {
  final count = 0.obs;
  final isTabOpen = false;
  final isLatestFirst = true.obs;

  @override
  void onClose() {}
  void increment() => count.value++;

  void toggleSortOrder() {
    isLatestFirst.value = !isLatestFirst.value;
    if (state != null && state!.isNotEmpty) {
      initOrderedTimeSlot();
    }
  }

  void sortTimeSlots(List<TimeSlot> timeSlots) {
    timeSlots.sort((a, b) {
      if (isLatestFirst.value) {
        return b.timeSlot!.compareTo(a.timeSlot!);
      } else {
        return a.timeSlot!.compareTo(b.timeSlot!);
      }
    });
  }

  Map<String, List<TimeSlot>> categorizeTimeSlots(List<TimeSlot> timeSlots) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final tomorrow = today.add(Duration(days: 1));

    Map<String, List<TimeSlot>> categorized = {
      'Upcoming': [],
      'Today': [],
      'Past': [],
    };

    for (var slot in timeSlots) {
      final slotDate = DateTime(
        slot.timeSlot!.year,
        slot.timeSlot!.month,
        slot.timeSlot!.day,
      );

      if (slotDate.isAfter(today)) {
        categorized['Upcoming']!.add(slot);
      } else if (slotDate.isAtSameMomentAs(today)) {
        categorized['Today']!.add(slot);
      } else {
        categorized['Past']!.add(slot);
      }
    }

    // Sort each category
    for (var category in categorized.values) {
      sortTimeSlots(category);
    }

    return categorized;
  }

  void initOrderedTimeSlot() {
    change({}, status: RxStatus.loading());
    TimeSlotService().getOrderedTimeSlot().then((value) {
      if (value.isEmpty) {
        change({}, status: RxStatus.empty());
        return;
      }
      final categorizedSlots = categorizeTimeSlots(value);
      change(categorizedSlots, status: RxStatus.success());
    }).catchError((err) {
      change({}, status: RxStatus.error());
    });
  }
}
