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 CaptainAdminController extends GetxController {
  bool isLoading = false;
  Map captainData = {};
  Map captain = {};
  final captainController = TextEditingController();
  final captainPrizeController = TextEditingController();
  final titleNotify = TextEditingController();
  final bodyNotify = TextEditingController();
  final formCaptainKey = GlobalKey<FormState>();
  final formCaptainPrizeKey = GlobalKey<FormState>();

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

    isLoading = false;
    update();
  }

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

    isLoading = false;
    update();
  }

  Future find_driver_by_phone(String phone) async {
    isLoading = true;
    update();
    var res = await CRUD().post(
      link: AppLink.find_driver_by_phone,
      payload: {'phone': "963$phone"},
    );
    var d = (res);
    if (d != 'failure') {
      captainData = d;
    } else {
      captainData = {};
      Get.snackbar('Error', 'No captain found with this phone number',
          backgroundColor: AppColor.redColor);
    }

    isLoading = false;
    update();
  }

  Future addCaptainPrizeToWallet() async {
    String? paymentId;
    //todo link to add wallet to captain
    for (var i = 0; i < captainData['message'].length; i++) {
      await CRUD().post(link: AppLink.addDriverPaymentPoints, payload: {
        'driverID': captainData['message'][i]['id'],
        'amount': captainPrizeController.text,
        'paymentMethod': 'Prize',
      }).then((value) {
        paymentId = value['message'].toString();
      });
      await CRUD().post(link: AppLink.addPassengersWallet, payload: {
        'driverID': captainData['message'][i]['id'],
        'amount': captainPrizeController.text,
        'paymentMethod': 'Prize',
        'paymentID': paymentId.toString(),
      });
    }

    Get.back();
  }

  void addCaptainsPrizeToWalletSecure() 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 addCaptainPrizeToWallet();
          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 addCaptainPrizeToWallet();
        Get.snackbar('Prize Added', '', backgroundColor: AppColor.greenColor);
      }
    } catch (e) {
      rethrow;
    }
  }

  Future getCaptains() async {
    var res = await CRUD()
        .get(link: AppLink.getCaptainDetailsByEmailOrIDOrPhone, payload: {
      'driver_id': captainController.text,
      'driverEmail': captainController.text,
      'driverPhone': captainController.text,
    });
    var d = jsonDecode(res);
    if (d['status'] == 'success') {
      captain = d;
    }
    update();
  }

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