import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

class TicketController extends GetxController {

  final ScrollController scrollController = ScrollController();

  @override
  void onInit() async{
    // TODO: implement onInit
    super.onInit();
    await fetchTicket();
  }

  RxString priorityValue = 'Select priority'.obs;
  RxList<String> priorityList = [
    'Select priority',
    'Urgent',
    'High',
    'Medium',
    'Low',
  ].obs;

  RxBool isLoading = false.obs;
  RxList<Map<String, dynamic>> ticketList = <Map<String, dynamic>>[].obs;

  Future<void> fetchTicket() async {

    isLoading(true);
    ticketList.clear();
    final ref = FirebaseDatabase.instance.ref('ticket');

    try {
      final snapshot = await ref.get();

      if (snapshot.exists && snapshot.value != null) {
        final value = snapshot.value;

        // Case 1: Firebase returns a Map (most common)
        if (value is Map) {
          ticketList.value = value.entries
              .map((entry) => {
            'id': entry.key,
            ...Map<String, dynamic>.from(entry.value as Map)
          })
              .toList();
        }

        // Case 2: Firebase returns a List
        else if (value is List) {
          ticketList.value = value
              .whereType<Map>() // filter nulls or invalid items
              .map((e) => Map<String, dynamic>.from(e))
              .toList();
        }

        debugPrint("✅ Loaded ${ticketList.length} tickets");
      } else {
        ticketList.clear();
        debugPrint("⚠️ No ticket data found");
      }
    } catch (e, st) {
      debugPrint("❌ Error loading tickets: $e");
      debugPrintStack(stackTrace: st);
    }

    isLoading(false);
  }


  TextEditingController subjectController = TextEditingController();
  TextEditingController messageController = TextEditingController();

  void createTicket() async {
    await FirebaseDatabase.instance.ref("ticket/${ticketList.length+1}").set({
      "id": ticketList.length+1,
      "priority": priorityValue.value,
      'message': messageController.text,
      "subject": subjectController.text,
      "create_at": DateTime.now().toString(),
    }).then((value) {
      Get.snackbar(
        'Ticket Created.',
        'Ticket Create Successfully with subject ${subjectController.text}',
      );
      fetchTicket();
    },);

  }
}
