import 'dart:convert';
import 'package:siro_driver/constant/api_key.dart';
import 'package:siro_driver/constant/style.dart';
import 'package:siro_driver/controller/functions/tts.dart';
import 'package:siro_driver/controller/payment/paymob/paymob_response.dart';
import 'package:siro_driver/views/widgets/elevated_btn.dart';
import 'package:siro_driver/views/widgets/error_snakbar.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:local_auth/local_auth.dart';
import 'package:siro_driver/views/widgets/mydialoug.dart';

import '../../constant/box_name.dart';
import '../../constant/colors.dart';
import '../../constant/info.dart';
import '../../constant/links.dart';
import '../../main.dart';
import '../functions/crud.dart';
import '../functions/toast.dart';
import 'paymob/paymob_wallet.dart';

class PaymentController extends GetxController {
  bool isLoading = false;
  bool isWalletChecked = true;
  bool isCashChecked = false;
  bool isWalletFound = false;
  bool isPromoSheetDialogue = false;
  final formKey = GlobalKey<FormState>();
  final promo = TextEditingController();
  // double totalPassenger =
  //     double.parse(Get.find<MapDriverController>().totalPricePassenger);
  int? selectedAmount = 0;
  List<dynamic> totalPassengerWalletDetails = [];
  final walletphoneController = TextEditingController();
  String passengerTotalWalletAmount = '';
  String ip = '1';
  DateTime now = DateTime.now();
  late int timestamp;

  void updateSelectedAmount(int value) {
    selectedAmount = value;
    update();
  }

  void changePromoSheetDialogue() {
    isPromoSheetDialogue = !isPromoSheetDialogue;
    update();
  }

  getPassengerWallet() async {
    isLoading = true;
    update();

    await CRUD().getWallet(
        link: AppLink.getWalletByPassenger,
        payload: {'passenger_id': box.read(BoxName.passengerID)}).then((value) {
      box.write(BoxName.passengerWalletTotal,
          jsonDecode(value)['message'][0]['total'].toString());
    });
    isLoading = false;
    update();
  }

  addPassengerWallet() async {
    isLoading = true;
    update();
    // double sallaryAccountNowBeforeAdding =
    //     double.parse(box.read(BoxName.passengerWalletTotal).toString());
    await CRUD().postWallet(link: AppLink.addPassengersWallet, payload: {
      'passenger_id': box.read(BoxName.passengerID).toString(),
      'balance': selectedAmount.toString()
    }).then((value) {
      getPassengerWallet();
      // sallaryAccountNowBeforeAdding = sallaryAccountNowBeforeAdding +
      //     double.parse(selectedAmount.toString());
      // box.write(BoxName.passengerWalletTotal, sallaryAccountNowBeforeAdding);
    });

    isLoading = false;
    update();
  }

  // void onChangedPaymentMethodWallet(bool? value) {
  //   if (box.read(BoxName.passengerWalletTotal) == null ||
  //       double.parse(box.read(BoxName.passengerWalletTotal).toString()) <
  //           totalPassenger) {
  //     isWalletChecked = false;
  //     isWalletChecked ? isCashChecked = true : isCashChecked = true;
  //     update();
  //   } else {
  //     isWalletChecked = !isWalletChecked;
  //     isWalletChecked ? isCashChecked = false : isCashChecked = true;
  //     update();
  //   }
  // }

  // void onChangedPaymentMethodCash(bool? value) {
  //   if (box.read(BoxName.passengerWalletTotal) == null ||
  //       double.parse(box.read(BoxName.passengerWalletTotal)) < totalPassenger) {
  //     isWalletChecked = false;
  //     isCashChecked = !isCashChecked;
  //     isCashChecked ? isWalletChecked = false : isWalletChecked = false;
  //     update();
  //   } else {
  //     isCashChecked = !isCashChecked;
  //     isCashChecked ? isWalletChecked = false : isWalletChecked = true;
  //     update();
  //   }
  // }


// 'https://accept.paymob.com/unifiedcheckout/?publicKey=egy_pk_live_mbjDC9Ni6FSHKmsz8sOHiVk2xd7oWRve&clientSecret=egy_sk_live_c0904e9cf04506ae64f818d4e075b4a957e3713fdf7a22cb7da30a29e72442b5'

  Future<void> payWithPayMob(
      BuildContext context, String amount, currency, Function method) async {
    String newAmount = (double.parse(amount) * 100).toStringAsFixed(2);
    try {
      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) {
          final PaymobResponse? response = await PaymobPayment.instance.pay(
            context: context,
            currency: currency, //"EGP",
            amountInCents: newAmount, // 19.00 EGP

            billingData: PaymobBillingData(),
            onPayment: (PaymobResponse response) {},
          );

          if (response!.responseCode == 'APPROVED') {
            Get.defaultDialog(
              barrierDismissible: false,
              title: 'Payment Successful'.tr,
              titleStyle: AppStyle.title,
              content: Text(
                'The payment was approved.'.tr,
                style: AppStyle.title,
              ),
              confirm: MyElevatedButton(
                title: 'OK'.tr,
                kolor: AppColor.greenColor,
                onPressed: () async {
                  Get.back();
                  method();
                },
              ),
            );
          } else {
            Get.defaultDialog(
              barrierDismissible: false,
              // backgroundColor: AppColor.redColor,
              title: 'Payment Failed'.tr,
              content: Text(
                'The payment was not approved. Please try again.'.tr,
                textAlign: TextAlign.center,
                style: AppStyle.title,
              ),
              confirm: MyElevatedButton(
                title: 'OK'.tr,
                kolor: AppColor.redColor,
                onPressed: () async {
                  Get.back();
                },
              ),
            );
          }
        } else {
          Get.snackbar("Authentication Failed",
              "Please enable Face ID or Fingerprint in your settings.");

          // Authentication failed, handle accordingly
        }
      } else {
        MyDialog().getDialog('Biometric Authentication'.tr,
            'You should use Touch ID or Face ID to confirm payment'.tr, () {
          Get.back();
        });
        // Authentication failed, handle accordingly
      }
      // else {
      //   final PaymobResponse? response = await PaymobPayment.instance.pay(
      //     context: context,
      //     currency: currency, //"EGP",
      //     amountInCents: newAmount, // 19.00 EGP
      //     billingData: PaymobBillingData(),
      //     onPayment: (PaymobResponse response) {},
      //   );

      //   if (response!.responseCode == 'APPROVED') {
      //     Get.defaultDialog(
      //       barrierDismissible: false,
      //       title: 'Payment Successful'.tr,
      //       titleStyle: AppStyle.title,
      //       // backgroundColor: AppColor.greenColor,
      //       content: Text(
      //         'The payment was approved.'.tr,
      //         style: AppStyle.title,
      //       ),
      //       confirm: MyElevatedButton(
      //         kolor: AppColor.greenColor,
      //         title: 'OK'.tr,
      //         onPressed: () async {
      //           Get.back();
      //           method();
      //         },
      //       ),
      //     );
      //   } else {
      //     Get.defaultDialog(
      //       barrierDismissible: false,
      //       // backgroundColor: AppColor.redColor,
      //       title: 'Payment Failed'.tr,
      //       content: Column(
      //         children: [
      //           IconButton(
      //             onPressed: () {
      //               Get.find<TextToSpeechController>().speakText(
      //                 'The payment was not approved. Please try again.'.tr,
      //               );
      //             },
      //             icon: const Icon(Icons.headphones),
      //           ),
      //           Text(
      //             'The payment was not approved. Please try again.'.tr,
      //             textAlign: TextAlign.center,
      //             style: AppStyle.title,
      //           ),
      //           Text(
      //             '${'The reason is'.tr} ${response.message!.tr}',
      //             textAlign: TextAlign.center,
      //             style: AppStyle.title.copyWith(color: AppColor.redColor),
      //           ),
      //         ],
      //       ),
      //       confirm: MyElevatedButton(
      //         title: 'OK'.tr,
      //         kolor: AppColor.redColor,
      //         onPressed: () async {
      //           Get.back();
      //         },
      //       ),
      //     );
      //   }

      // }
    } catch (e) {
      Get.defaultDialog(
        title: 'Error'.tr,
        content: Text(
          'An error occurred during the payment process.'.tr,
          style: AppStyle.title,
        ),
      );
      rethrow;
    }
  }

  Future<void> payWithPayMobWallet(
      BuildContext context, String amount, currency, Function method) async {
    String newAmount = (double.parse(amount) * 100).toStringAsFixed(2);
    try {
      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) {
          final PaymobResponseWallet? response =
              await PaymobPaymentWallet.instance.pay(
            context: context,
            currency: currency, //"EGP",
            amountInCents: newAmount, // 19.00 EGP

            billingData: PaymobBillingDataWallet(),
            onPayment: (PaymobResponseWallet response) {},
          );
          if (response!.success == true &&
              response.message.toString() == 'Approved') {
            Toast.show(context, 'Payment Successful'.tr, AppColor.greenColor);
            method();
          } else {
            Get.defaultDialog(
              barrierDismissible: false,
              // backgroundColor: AppColor.redColor,
              title: 'Payment Failed'.tr,
              content: Column(
                children: [
                  IconButton(
                    onPressed: () {
                      Get.find<TextToSpeechController>().speakText(
                        'The payment was not approved. Please try again.'.tr,
                      );
                    },
                    icon: const Icon(Icons.headphones),
                  ),
                  Text(
                    'The payment was not approved. Please try again.'.tr,
                    textAlign: TextAlign.center,
                    style: AppStyle.title,
                  ),
                  Text(
                    '${'The reason is'.tr} ${response.message!.tr}',
                    textAlign: TextAlign.center,
                    style: AppStyle.title.copyWith(color: AppColor.redColor),
                  ),
                ],
              ),
              confirm: MyElevatedButton(
                title: 'OK'.tr,
                kolor: AppColor.redColor,
                onPressed: () async {
                  Get.back();
                },
              ),
            );
          }
        } else {
          // Authentication failed, handle accordingly
          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();
        });
        // final PaymobResponse? response = await PaymobPayment.instance.pay(
        //   context: context,
        //   currency: currency, //"EGP",
        //   amountInCents: newAmount, // 19.00 EGP
        //   billingData: PaymobBillingData(),
        //   onPayment: (PaymobResponse response) {},
        // );

        // // if (response!.responseCode == 'APPROVED') {
        // if (response!.responseCode == '200' && response.success == true) {
        //   Toast.show(context, 'Payment Successful'.tr, AppColor.greenColor);
        //   method();
        // Get.defaultDialog(
        //   barrierDismissible: false,
        //   title: 'Payment Successful'.tr,
        //   titleStyle: AppStyle.title,
        //   // backgroundColor: AppColor.greenColor,
        //   content: Text(
        //     'The payment was approved.'.tr,
        //     style: AppStyle.title,
        //   ),
        //   confirm: MyElevatedButton(
        //     kolor: AppColor.greenColor,
        //     title: 'OK'.tr,
        //     onPressed: () async {
        //       Get.back();
        //       method();
        //     },
        //   ),
        // );
        // } else {
        //   Get.defaultDialog(
        //     barrierDismissible: false,
        //     // backgroundColor: AppColor.redColor,
        //     title: 'Payment Failed'.tr,
        //     content: Text(
        //       'The payment was not approved. Please try again.'.tr,
        //       textAlign: TextAlign.center,
        //       style: AppStyle.title,
        //     ),
        //     confirm: MyElevatedButton(
        //       title: 'OK'.tr,
        //       kolor: AppColor.redColor,
        //       onPressed: () async {
        //         Get.back();
        //       },
        //     ),
        //   );
        // }
      }
    } catch (e) {
      Get.defaultDialog(
        title: 'Error'.tr,
        content: Text(
          'An error occurred during the payment process.'.tr,
          style: AppStyle.title,
        ),
      );
      rethrow;
    }
  }

  @override
  void onInit() {
    timestamp = now.millisecondsSinceEpoch;
    if (box.read(BoxName.passengerWalletTotal) == null) {
      box.write(BoxName.passengerWalletTotal, '0');
    }
    // getPassengerWallet();
    super.onInit();
  }
}
