import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:local_auth/local_auth.dart';

import '../../constant/colors.dart';
import '../../constant/links.dart';
import '../functions/crud.dart';

class PassengerAdminController extends GetxController {
  bool isLoading = false;
  Map passengersData = {};
  Map passengers = {};
  double height = 150;
  final formPassKey = GlobalKey<FormState>();
  final formPrizeKey = GlobalKey<FormState>();
  final titleNotify = TextEditingController();
  final bodyNotify = TextEditingController();
  final passengerController = TextEditingController();
  final passengerPrizeController = TextEditingController();

  Future getPassengerCount() async {
    isLoading = true;
    update();
    var res = await CRUD().get(link: AppLink.getPassengerDetails, payload: {});
    var d = jsonDecode(res);
    if (d['status'] == 'success') {
      passengersData = d;
    }

    isLoading = false;
    update();
  }

  Future addPassengerPrizeToWallet() async {
    for (var i = 0; i < passengersData['message'].length; i++) {
      await CRUD().post(link: AppLink.addPassengersWallet, payload: {
        'passenger_id': passengersData['message'][i]['id'],
        'balance': passengerPrizeController.text,
      });
    }

    Get.back();
  }
// داخل الـController نفسه

  Future<bool> updatePassenger({
    required String id, // أو مرّر phoneLookup بدل id لو حاب
    String? firstName,
    String? lastName,
    String? phone,
  }) async {
    // لا نرسل طلب إذا ما في أي تغيير
    if ((firstName == null || firstName.trim().isEmpty) &&
        (lastName == null || lastName.trim().isEmpty) &&
        (phone == null || phone.trim().isEmpty)) {
      return false;
    }

    // فلتر بسيط للأرقام فقط
    // String _normalizePhone(String s) => s.replaceAll(RegExp(r'\D+'), '');

    final Map<String, dynamic> payload = {
      'id':
          id, // لو بدك تستخدم phone_lookup بدل id: احذف هذا وأرسل {'phone_lookup': phoneLookup}
    };

    if (firstName != null && firstName.trim().isNotEmpty) {
      payload['first_name'] = firstName.trim();
    }
    if (lastName != null && lastName.trim().isNotEmpty) {
      payload['last_name'] = lastName.trim();
    }
    if (phone != null && phone.trim().isNotEmpty) {
      payload['phone'] = (phone);
    }

    // حالة تحميل
    isLoading = true;
    update();

    try {
      final res = await CRUD().post(
        link: AppLink.admin_update_passenger, // عدّل الرابط حسب اسم مسارك
        payload: payload,
      );
      final d = (res);

      final ok = (d['status'] == 'success');
      if (ok) {
        // (اختياري) حدّث الكاش/الواجهة — مثلاً أعد الجلب
        Get.snackbar('Update successful',
            d['message']?.toString() ?? 'Passenger updated successfully',
            backgroundColor: AppColor.greenColor);
        // await getPassengerCount(); // أو حدّث passengersData محليًا إذا متاح
      } else {
        // (اختياري) أظهر رسالة خطأ
        // Get.snackbar('Update failed', d['message']?.toString() ?? 'Unknown error');
      }
      return ok;
    } catch (e) {
      // Get.snackbar('Error', e.toString());
      return false;
    } finally {
      isLoading = false;
      update();
    }
  }

  void addPassengerPrizeToWalletSecure() async {
    try {
      // Check if local authentication is available
      bool isAvailable = await LocalAuthentication().isDeviceSupported();
      if (isAvailable) {
        // Authenticate the user
        bool didAuthenticate = await LocalAuthentication().authenticate(
          localizedReason: 'Use Touch ID or Face ID to confirm payment',
        );
        if (didAuthenticate) {
          // User authenticated successfully, proceed with payment
          await addPassengerPrizeToWallet();
          Get.snackbar('Prize Added', '', backgroundColor: AppColor.greenColor);
        } else {
          // Authentication failed, handle accordingly
          Get.snackbar('Authentication failed', '',
              backgroundColor: AppColor.redColor);
          //     'Authentication failed');
        }
      } else {
        // Local authentication not available, proceed with payment without authentication
        await addPassengerPrizeToWallet();
        Get.snackbar('Prize Added', '', backgroundColor: AppColor.greenColor);
      }
    } catch (e) {
      rethrow;
    }
  }

  Future getPassengers() async {
    var res = await CRUD().get(link: AppLink.getPassengerbyEmail, payload: {
      'passengerEmail': passengerController.text,
      'passengerId': passengerController.text,
      'passengerphone': passengerController.text,
    });
    var d = jsonDecode(res);
    if (d['status'] == 'success') {
      passengers = d;
    }
    update();
  }

  changeHeight() {
    if (passengers.isEmpty) {
      height = 0;
      update();
    }
    height = 150;
    update();
  }

  void clearPlaces() {
    passengers = {};
    update();
  }

  @override
  void onInit() {
    getPassengerCount();
    super.onInit();
  }
}
