import 'package:Intaleq/constant/style.dart';
import 'package:Intaleq/controller/functions/encrypt_decrypt.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/constant/colors.dart';
import 'package:Intaleq/controller/functions/toast.dart';
import 'package:Intaleq/controller/payment/payment_controller.dart';
import 'package:local_auth/local_auth.dart';

import '../../../main.dart';
import '../../widgets/elevated_btn.dart';
import '../../widgets/my_textField.dart';
import 'payment_screen_sham.dart';

class PassengerWalletDialog extends StatelessWidget {
  const PassengerWalletDialog({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return GetBuilder<PaymentController>(
      builder: (controller) => Positioned(
        top: Get.height * .1,
        right: Get.width * .15,
        left: Get.width * .15,
        bottom: Get.height * .1,
        child: controller.isPromoSheetDialogue
            ? CupertinoActionSheet(
                title: Text('Select Payment Amount'.tr),
                actions: [
                  CupertinoActionSheetAction(
                    onPressed: () {
                      controller.updateSelectedAmount(
                        box.read(BoxName.countryCode) == 'Syria' ? 10000 : 10,
                      );
                      showPaymentOptions(context, controller);
                    },
                    child: Text(
                      box.read(BoxName.countryCode) == 'Syria'
                          ? '10000 ${'LE'.tr}'
                          : '10 ${'SYP'.tr}',
                    ),
                  ),
                  CupertinoActionSheetAction(
                    onPressed: () {
                      controller.updateSelectedAmount(
                        box.read(BoxName.countryCode) == 'Syria' ? 20000 : 20,
                      );
                      showPaymentOptions(context, controller);
                    },
                    child: Text(
                      box.read(BoxName.countryCode) == 'Syria'
                          ? '20000 ${'LE'.tr} = 2050 ${'LE'.tr}'
                          : '20 ${'SYP'.tr}',
                    ),
                  ),
                  CupertinoActionSheetAction(
                    onPressed: () {
                      controller.updateSelectedAmount(
                        box.read(BoxName.countryCode) == 'Syria' ? 40000 : 40,
                      );
                      showPaymentOptions(context, controller);
                    },
                    child: Text(
                      box.read(BoxName.countryCode) == 'Syria'
                          ? '40000 ${'LE'.tr} = 4150 ${'LE'.tr}'
                          : '40 ${'SYP'.tr}',
                    ),
                  ),
                  CupertinoActionSheetAction(
                    onPressed: () {
                      controller.updateSelectedAmount(
                        box.read(BoxName.countryCode) == 'Syria' ? 100000 : 50,
                      );
                      showPaymentOptions(context, controller);
                    },
                    child: Text(
                      box.read(BoxName.countryCode) == 'Syria'
                          ? '100000 ${'LE'.tr} = 11000 ${'LE'.tr}'
                          : '50 ${'SYP'.tr}',
                    ),
                  ),
                ],
                cancelButton: CupertinoActionSheetAction(
                  onPressed: () {
                    controller.changePromoSheetDialogue();
                  },
                  child: Text('Cancel'.tr),
                ),
              )
            : const SizedBox(),
      ),
    );
  }
}
// class PassengerWalletDialog extends StatelessWidget {
//   const PassengerWalletDialog({
//     super.key,
//   });

//   @override
//   Widget build(BuildContext context) {
//     return GetBuilder<PaymentController>(
//       builder: (controller) {
//         return Positioned(
//           top: Get.height * .1,
//           right: Get.width * .15,
//           left: Get.width * .15,
//           bottom: Get.height * .1,
//           child: controller.isPromoSheetDialogue
//               ? Container()
//               : SizedBox
//                   .shrink(), // If condition is false, return an empty widget
//         );
//       },
//     );
//   }
// }
void showPaymentBottomSheet(BuildContext context) {
  final controller = Get.find<PaymentController>();

  showModalBottomSheet(
    context: context,
    isScrollControlled: true,
    shape: const RoundedRectangleBorder(
      borderRadius: BorderRadius.vertical(top: Radius.circular(15.0)),
    ),
    builder: (BuildContext context) {
      return WillPopScope(
        onWillPop: () async {
          Get.back();
          return false;
        },
        child: Container(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Text(
                'Select Payment Amount'.tr,
                style: AppStyle.headTitle2,
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16.0),

              // Payment Options List
              _buildPaymentOption(
                context: context,
                controller: controller,
                amount: 500,
                bonusAmount: 30,
                currency: 'SYP'.tr,
              ),

              const SizedBox(height: 8.0),
              _buildPaymentOption(
                context: context,
                controller: controller,
                amount: 1000,
                bonusAmount: 70,
                currency: 'SYP'.tr,
              ),

              const SizedBox(height: 8.0),
              _buildPaymentOption(
                context: context,
                controller: controller,
                amount: 2000,
                bonusAmount: 180,
                currency: 'SYP'.tr,
              ),

              const SizedBox(height: 8.0),
              _buildPaymentOption(
                context: context,
                controller: controller,
                amount: 5000,
                bonusAmount: 700,
                currency: 'SYP'.tr,
              ),

              const SizedBox(height: 16.0),
              TextButton(
                onPressed: () => Get.back(),
                child: Text('Cancel'.tr),
              ),
            ],
          ),
        ),
      );
    },
  );
}

Widget _buildPaymentOption({
  required BuildContext context,
  required PaymentController controller,
  required int amount,
  required double bonusAmount,
  required String currency,
}) {
  return Material(
    color: Colors.transparent,
    child: InkWell(
      onTap: () {
        controller.updateSelectedAmount(amount);
        Get.back();
        showPaymentOptions(context, controller);
      },
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey[300]!),
          borderRadius: BorderRadius.circular(8.0),
        ),
        child: Text(
          bonusAmount > 0
              ? '${'Pay'.tr} $amount $currency, ${'Get'.tr} ${amount + bonusAmount} $currency'
              : '$amount $currency',
          style: AppStyle.title,
          textAlign: TextAlign.center,
        ),
      ),
    ),
  );
}

void showPaymentOptions(BuildContext context, PaymentController controller) {
  showCupertinoModalPopup(
    context: context,
    builder: (context) => CupertinoActionSheet(
      title: Text('Payment Options'.tr),
      actions: [
        box.read(BoxName.countryCode) == 'Syria'
            ? CupertinoActionSheetAction(
                child: Text('💳 Pay with Credit Card'.tr),
                onPressed: () async {
                  if (controller.selectedAmount != 0) {
                    controller.payWithEcash(
                      context,
                      controller.selectedAmount.toString(),
                      // () async {
                      //   await controller.addPassengerWallet();
                      //   controller.changePromoSheetDialogue();
                    );
                    await controller.getPassengerWallet();
                  } else {
                    Toast.show(context, '⚠️ You need to choose an amount!'.tr,
                        AppColor.redColor);
                  }
                },
              )
            : const SizedBox(),
        box.read(BoxName.countryCode) != 'Syria'
            ? CupertinoActionSheetAction(
                child: Text('Pay with PayPal'.tr),
                onPressed: () {
                  if (controller.selectedAmount != 0) {
                    controller.makePaymentPayPal(context);
                  } else {
                    Toast.show(context, 'You will choose one of above!'.tr,
                        AppColor.redColor);
                  }
                },
              )
            : const SizedBox(),
        //   box.read(BoxName.phoneWallet) != null
        //       ? CupertinoActionSheetAction(
        //           child: Text('💰 Pay with Wallet'.tr),
        //           onPressed: () async {
        //             if (controller.selectedAmount != 0) {
        //               controller.isLoading = true;
        //               controller.update();
        //               controller.payWithMTNWallet(
        //                 context,
        //                 controller.selectedAmount.toString(),
        //                 'SYP',
        //               );
        //               await controller.getPassengerWallet();
        //               controller.isLoading = false;
        //               controller.update();
        //             } else {
        //               Toast.show(context, '⚠️ You need to choose an amount!'.tr,
        //                   AppColor.redColor);
        //             }
        //           },
        //         )
        //       : CupertinoActionSheetAction(
        //           child: Text('Add wallet phone you use'.tr),
        //           onPressed: () {
        //             Get.dialog(
        //               CupertinoAlertDialog(
        //                 title: Text('Insert Wallet phone number'.tr),
        //                 content: Column(
        //                   children: [
        //                     const SizedBox(height: 10),
        //                     CupertinoTextField(
        //                       controller: controller.walletphoneController,
        //                       placeholder: 'Insert Wallet phone number'.tr,
        //                       keyboardType: TextInputType.phone,
        //                       padding: const EdgeInsets.symmetric(
        //                         vertical: 12,
        //                         horizontal: 10,
        //                       ),
        //                     ),
        //                   ],
        //                 ),
        //                 actions: [
        //                   CupertinoDialogAction(
        //                     child: Text('Cancel'.tr,
        //                         style: const TextStyle(
        //                             color: CupertinoColors.destructiveRed)),
        //                     onPressed: () {
        //                       Get.back();
        //                     },
        //                   ),
        //                   CupertinoDialogAction(
        //                     child: Text('OK'.tr,
        //                         style: const TextStyle(
        //                             color: CupertinoColors.activeGreen)),
        //                     onPressed: () async {
        //                       Get.back();
        //                       box.write(BoxName.phoneWallet,
        //                           (controller.walletphoneController.text));
        //                       Toast.show(
        //                           context,
        //                           'Phone Wallet Saved Successfully'.tr,
        //                           AppColor.greenColor);
        //                     },
        //                   ),
        //                 ],
        //               ),
        //               barrierDismissible: false,
        //             );
        //           },
        //         ),
        // GestureDetector(
        //     onTap: () async {
        //       Get.back();
        //       Get.defaultDialog(
        //           barrierDismissible: false,
        //           title: 'Insert Wallet phone number'.tr,
        //           content: Form(
        //               key: controller.formKey,
        //               child: MyTextForm(
        //                   controller: controller.walletphoneController,
        //                   label: 'Insert Wallet phone number'.tr,
        //                   hint: '963941234567',
        //                   type: TextInputType.phone)),
        //           confirm: MyElevatedButton(
        //               title: 'OK'.tr,
        //               onPressed: () async {
        //                 Get.back();
        //                 if (controller.formKey.currentState!.validate()) {
        //                   if (controller.selectedAmount != 0) {
        //                     controller.isLoading = true;
        //                     controller.update();
        //                     box.write(BoxName.phoneWallet,
        //                         (controller.walletphoneController.text));
        //                     Get.back();
        //                     await controller.payWithMTNWallet(
        //                       context,
        //                       controller.selectedAmount.toString(),
        //                       'SYP',
        //                     );
        //                     await controller.getPassengerWallet();

        //                     controller.isLoading = false;
        //                     controller.update();
        //                   } else {
        //                     Toast.show(
        //                       context,
        //                       '⚠️ You need to choose an amount!'.tr,
        //                       AppColor.redColor,
        //                     );
        //                   }
        //                 }
        //               }));
        //     },
        //     child: Padding(
        //       padding: const EdgeInsets.all(8.0),
        //       child: Row(
        //         mainAxisAlignment: MainAxisAlignment.spaceBetween,
        //         children: [
        //           Text(
        //             'Pay by MTN Wallet'.tr,
        //             style: AppStyle.title,
        //           ),
        //           const SizedBox(width: 10),
        //           Image.asset(
        //             'assets/images/cashMTN.png',
        //             width: 70,
        //             height: 70,
        //             fit: BoxFit.contain,
        //           ),
        //         ],
        //       ),
        //     )),

        GestureDetector(
            onTap: () async {
              Get.back();
              Get.defaultDialog(
                  barrierDismissible: false,
                  title: 'Insert Wallet phone number'.tr,
                  content: Form(
                      key: controller.formKey,
                      child: MyTextForm(
                          controller: controller.walletphoneController,
                          label: 'Insert Wallet phone number'.tr,
                          hint: '963941234567',
                          type: TextInputType.phone)),
                  confirm: MyElevatedButton(
                      title: 'OK'.tr,
                      onPressed: () async {
                        Get.back();
                        if (controller.formKey.currentState!.validate()) {
                          box.write(BoxName.phoneWallet,
                              controller.walletphoneController.text);
                          await controller.payWithSyriaTelWallet(
                              controller.selectedAmount.toString(), 'SYP');
                        }
                      }));
            },
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    'Pay by Syriatel Wallet'.tr,
                    style: AppStyle.title,
                  ),
                  const SizedBox(width: 10),
                  Image.asset(
                    'assets/images/syriatel.png',
                    width: 70,
                    height: 70,
                    fit: BoxFit.fill,
                  ),
                ],
              ),
            )),
        GestureDetector(
            onTap: () async {
              // التحقق بالبصمة قبل أي شيء
              bool isAuthSupported =
                  await LocalAuthentication().isDeviceSupported();

              if (isAuthSupported) {
                bool didAuthenticate = await LocalAuthentication().authenticate(
                  localizedReason: 'استخدم بصمة الإصبع أو الوجه لتأكيد الدفع',
                );

                if (!didAuthenticate) {
                  print("❌ User did not authenticate with biometrics");
                  return;
                }
              }

              // الانتقال مباشرة لإنشاء الفاتورة بعد النجاح بالبصمة
              Get.to(() => PaymentScreenSmsProvider(
                  amount: double.parse(controller.selectedAmount.toString())));
            },
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    'Pay by Sham Cash'.tr,
                    style: AppStyle.title,
                  ),
                  const SizedBox(width: 10),
                  Image.asset(
                    'assets/images/shamCash.png',
                    width: 70,
                    height: 70,
                    fit: BoxFit.fill,
                  ),
                ],
              ),
            )),
      ],
      cancelButton: CupertinoActionSheetAction(
        child: Text('Cancel'.tr),
        onPressed: () {
          // controller.changePromoSheetDialogue();
          Get.back();
        },
      ),
    ),
  );
}
