import 'dart:convert';

import 'package:local_auth/local_auth.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/controller/payment/smsPaymnet/payment_services.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:get/get.dart';

import '../../../constant/links.dart';
import '../../../views/widgets/mydialoug.dart';
import '../../functions/crud.dart';
import 'captain_wallet_controller.dart';

class PaymobPayout extends GetxController {
  bool isLoading = false;
  String dropdownValue = 'etisalat';

  int payOutFee = 5;
  payToDriverWallet(String amount, String issuer, String msisdn) async {
    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',
        // options: AuthenticationOptions(
        biometricOnly: true,
        sensitiveTransaction: true,
      );
      if (didAuthenticate) {
        // var dec = await CRUD()
        //     .postWallet(link: AppLink.paymobPayoutDriverWallet, payload: {
        //   "issuer": issuer,
        //   "method": "wallet",
        //   "amount": amount, //9.0,
        //   "full_name":
        //       '${box.read(BoxName.nameDriver)} ${box.read(BoxName.lastNameDriver)}',
        //   "msisdn": msisdn, //"01010101010",
        //   "bank_transaction_type": "cash_transfer"
        // });
        // if (dec['disbursement_status'] == 'successful') {
        //   var paymentToken = await Get.find<CaptainWalletController>()
        //       .generateToken(
        //           ((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
        //               .toStringAsFixed(0));
        //   await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
        //     'rideId': DateTime.now().toIso8601String(),
        //     'amount':
        //         ((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
        //             .toStringAsFixed(0),
        //     'payment_method': 'payout',
        //     'passengerID': 'myself',
        //     'token': paymentToken,
        //     'driverID': box.read(BoxName.driverID).toString(),
        //   });
        //   await Get.find<CaptainWalletController>()
        //       .addSeferWallet('payout fee myself', payOutFee.toString());
        //   await updatePaymentToPaid(box.read(BoxName.driverID).toString());
        //   await sendEmail(
        //       box.read(BoxName.driverID).toString(),
        //       amount,
        //       box.read(BoxName.phoneDriver).toString(),
        //       box.read(BoxName.nameDriver).toString(),
        //       'Wallet',
        //       box.read(BoxName.emailDriver).toString());

        //   mySnackbarSuccess('${'Transaction successful'.tr} ${dec['amount']}');

        //   Get.find<CaptainWalletController>().refreshCaptainWallet();
        // } else if (dec['disbursement_status'] == 'failed') {
        //   mySnackeBarError('Transaction failed'.tr);
        // }
      } else {
        MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
          Get.back();
        });
      }
    } else {
      MyDialog().getDialog('Biometric Authentication'.tr,
          'You should use Touch ID or Face ID to confirm payment'.tr, () {
        Get.back();
      });
    }
  }

  Future updatePaymentToPaid(String driverID) async {
    await CRUD().postWallet(link: AppLink.updatePaymetToPaid, payload: {
      'driverID': driverID.toString(),
    });
  }

  Future sendEmail(
      String driverId, amount, phone, name, bankCardNumber, email) async {
    await CRUD().sendEmail(AppLink.sendEmailToDrivertransaction, {
      "driverID": driverId,
      "total_amount": amount,
      "phone": phone,
      "name_arabic": name,
      "accountBank": bankCardNumber,
      "email": email
    });
  }

  getAIKey(String key) async {
    var res =
        await CRUD().get(link: AppLink.getapiKey, payload: {"keyName": key});
    if (res != 'failure') {
      var d = jsonDecode(res)['message'];
      return d[key].toString();
    } else {}
  }

  payToDriverBankAccount(
      String amount, String bankCardNumber, String bankCode) async {
    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',
        // options: AuthenticationOptions(
        biometricOnly: true,
        sensitiveTransaction: true,
      );
      if (didAuthenticate) {
        var body = {
          "issuer": "bank_card",
          "method": "bank_card",
          "amount": amount, //9.0,
          "full_name":
              '${box.read(BoxName.nameDriver)} ${box.read(BoxName.lastNameDriver)}',
          "bank_card_number": bankCardNumber, //"1111-2222-3333-4444",
          "bank_code": bankCode, //"CIB",
          "bank_transaction_type": "cash_transfer"
        };
        var dec = await CRUD().postWallet(
          link:
              'wl.tripz-egypt.com/v1/main/ride/payMob/paymob_driver/paymob_payout.php',
          payload: body,
        );
        if (dec['disbursement_status'] == 'successful') {
          var paymentToken = await Get.find<CaptainWalletController>()
              .generateToken(
                  ((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
                      .toStringAsFixed(0));
          await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
            'rideId': DateTime.now().toIso8601String(),
            'amount':
                ((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
                    .toStringAsFixed(0),
            'payment_method': 'payout',
            'passengerID': 'myself',
            'token': paymentToken,
            'driverID': box.read(BoxName.driverID).toString(),
          });
          await Get.find<CaptainWalletController>()
              .addSeferWallet('payout fee myself', payOutFee.toString());
          await updatePaymentToPaid(box.read(BoxName.driverID).toString());
          await sendEmail(
              box.read(BoxName.driverID).toString(),
              amount,
              box.read(BoxName.phoneDriver).toString(),
              box.read(BoxName.nameDriver).toString(),
              'Wallet',
              box.read(BoxName.emailDriver).toString());

          mySnackbarSuccess('${'Transaction successful'.tr} ${dec['amount']}');
          Get.find<CaptainWalletController>().refreshCaptainWallet();
        } else if (dec['disbursement_status'] == 'failed') {
          mySnackeBarError('Transaction failed'.tr);
        }
      } else {
        MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
          Get.back();
        });
      }
    } else {
      MyDialog().getDialog('Biometric Authentication'.tr,
          'You should use Touch ID or Face ID to confirm payment'.tr, () {
        Get.back();
      });
    }
  }

  Future payToWalletDriverAll(
      String amount, String issuer, String msisdn) async {
    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',
        // options: AuthenticationOptions(
        biometricOnly: true,
        sensitiveTransaction: true,
      );
      if (didAuthenticate) {
        await payToDriverWallet(amount, issuer, msisdn);
      } else {
        MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
          Get.back();
        });
      }
    } else {
      MyDialog().getDialog('Biometric Authentication'.tr,
          'You should use Touch ID or Face ID to confirm payment'.tr, () {
        Get.back();
      });
    }
  }

  Future payToBankDriverAll(
      String amount, String bankCardNumber, String bankCode) async {
    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',
        // options: AuthenticationOptions(
        biometricOnly: true,
        sensitiveTransaction: true,
      );
      if (didAuthenticate) {
        await payToDriverBankAccount(amount, bankCardNumber, bankCode);
      } else {
        MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
          Get.back();
        });
      }
    } else {
      MyDialog().getDialog('Biometric Authentication'.tr,
          'You should use Touch ID or Face ID to confirm payment'.tr, () {
        Get.back();
      });
    }
  }
}
