import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:siro_rider/constant/box_name.dart';
import 'package:siro_rider/controller/functions/secure_storage.dart';
import 'package:siro_rider/controller/home/payment/credit_card_controller.dart';
import 'package:siro_rider/views/widgets/elevated_btn.dart';

import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/home/map/map_engine_controller.dart';

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

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MapEngineController>(
        builder: (controller) => Positioned(
              right: 5,
              bottom: 5,
              left: 5,
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 400),
                height: controller.isPaymentMethodPageShown
                    ? controller.paymentPageShown
                    : 0,
                decoration: BoxDecoration(
                    color: AppColor.secondaryColor,
                    borderRadius: BorderRadius.circular(15)),
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            'My Card'.tr,
                            style: AppStyle.title.copyWith(fontSize: 22),
                          ),
                          IconButton(
                            onPressed: () =>
                                controller.changePaymentMethodPageShown(),
                            icon: const Icon(Icons.close),
                          ),
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            'Add Card'.tr,
                            style: AppStyle.title,
                          ),
                          // GetBuilder<CreditCardController>(
                          //   builder: (controller) => IconButton(
                          //     onPressed: () {
                          //       // controller.scanCard();
                          //       // Get.defaultDialog(content: OptionConfigureWidget(
                          //       //     initialOptions: scanOptions,
                          //       //     onScanOptionChanged: (newOptions) =>
                          //       //         scanOptions = newOptions,
                          //       //   ),
                          //       // );
                          //     },
                          //     icon: const Icon(Icons.contact_emergency_sharp),
                          //   ),
                          // )
                        ],
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      const MyCreditCardWidget(),
                      const Spacer(),
                      GetBuilder<CreditCardController>(
                          builder: (controller) => Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  MyElevatedButton(
                                    title: 'Add Credit Card'.tr,
                                    onPressed: () async {
                                      if (controller.formKey.currentState!
                                          .validate()) {
                                        SecureStorage().saveData(
                                            BoxName.cardNumber,
                                            controller
                                                .cardNumberController.text);
                                        SecureStorage().saveData(
                                            BoxName.cardHolderName,
                                            controller
                                                .cardHolderNameController.text);
                                        SecureStorage().saveData(
                                            BoxName.cvvCode,
                                            controller.cvvCodeController.text);
                                        SecureStorage().saveData(
                                            BoxName.expiryDate,
                                            controller
                                                .expiryDateController.text);
                                      }
                                    },
                                  ),
                                ],
                              ))
                    ],
                  ),
                ),
              ),
            ));
  }
}

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

  @override
  Widget build(BuildContext context) {
    Get.put(CreditCardController());
    return GetBuilder<CreditCardController>(
        builder: (controller) => Container(
            height: Get.height * .4,
            width: Get.width * .9,
            decoration: BoxDecoration(
              color: AppColor.secondaryColor,
              borderRadius: const BorderRadius.all(Radius.circular(15)),
              gradient: LinearGradient(colors: [
                AppColor.secondaryColor,
                // AppColor.blueColor,
                // AppColor.greenColor,
                AppColor.accentColor,
                // AppColor.primaryColor,
                // AppColor.redColor,
                // AppColor.yellowColor
              ]),
              boxShadow: const [
                BoxShadow(
                    spreadRadius: 3,
                    offset: Offset(3, 3),
                    blurRadius: 3,
                    color: AppColor.redColor),
                BoxShadow(
                    offset: Offset(-3, -3),
                    blurRadius: 3,
                    spreadRadius: 3,
                    color: AppColor.redColor),
              ],
            ),
            child: Form(
                key: controller.formKey,
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      SizedBox(
                        child: Row(
                          children: [
                            getCardIcon(controller.cardNumberController
                                .text), // Dynamic credit card icon
                            SizedBox(
                              width: Get.width * .03,
                            ),
                            SizedBox(
                              width: Get.width * .25,
                              child: Text(
                                'Card Number'.tr,
                                style: AppStyle.title,
                              ),
                            ),
                            SizedBox(
                              width: Get.width * .03,
                            ),
                            SizedBox(
                              width: Get.width * .4,
                              height: 70,
                              child: TextFormField(
                                maxLength: 16,
                                keyboardType: TextInputType.number,
                                controller: controller.cardNumberController,
                                style: const TextStyle(
                                    color: AppColor.blueColor,
                                    fontFamily: 'digital-counter-7',
                                    fontWeight: FontWeight.bold),
                                decoration: const InputDecoration(
                                  helperStyle: TextStyle(
                                      fontFamily: 'digital-counter-7'),
                                  // labelText: 'Card Number',
                                ),
                                // inputFormatters: [DigitObscuringFormatter()],
                                validator: (value) {
                                  if (value!.isEmpty || value.length != 16) {
                                    return 'Please enter a valid 16-digit card number'
                                        .tr;
                                  }
                                  return null;
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                      Row(
                        children: [
                          const Icon(Icons.person),
                          SizedBox(
                            width: Get.width * .03,
                          ),
                          SizedBox(
                            width: Get.width * .25,
                            child: Text(
                              'Holder Name',
                              style: AppStyle.title,
                            ),
                          ),
                          SizedBox(
                            width: Get.width * .03,
                          ),
                          SizedBox(
                            width: Get.width * .3,
                            child: SizedBox(
                              // height: 50,
                              child: TextFormField(
                                style: AppStyle.title,
                                keyboardType: TextInputType.text,
                                // maxLength: 16,
                                controller: controller.cardHolderNameController,
                                decoration: const InputDecoration(
                                    // labelText: 'Cardholder Name',
                                    ),
                                validator: (value) {
                                  if (value!.isEmpty) {
                                    return 'Please enter the cardholder name'
                                        .tr;
                                  }
                                  return null;
                                },
                              ),
                            ),
                          )
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(
                            width: Get.width * .4,
                            child: Row(
                              children: [
                                const Icon(Icons.date_range_outlined),
                                SizedBox(
                                  width: Get.width * .03,
                                ),
                                Column(
                                  children: [
                                    SizedBox(
                                      width: Get.width * .2,
                                      child: Text(
                                        'Expiry Date',
                                        style: AppStyle.subtitle,
                                      ),
                                    ),
                                    SizedBox(
                                      width: Get.width * .1,
                                      child: SizedBox(
                                        height: 60,
                                        child: TextFormField(
                                          maxLength: 4,
                                          keyboardType: TextInputType.datetime,
                                          controller:
                                              controller.expiryDateController,
                                          style: AppStyle.title,
                                          decoration: const InputDecoration(),
                                          validator: (value) {
                                            if (value!.isEmpty) {
                                              return 'Please enter the expiry date'
                                                  .tr;
                                            }
                                            return null;
                                          },
                                        ),
                                      ),
                                    )
                                  ],
                                ),
                              ],
                            ),
                          ),
                          SizedBox(
                            width: Get.width * .4,
                            child: Row(
                              children: [
                                const Icon(Icons.security),
                                SizedBox(
                                  width: Get.width * .021,
                                ),
                                Column(
                                  children: [
                                    SizedBox(
                                      width: Get.width * .2,
                                      child: Text(
                                        'CVV Code',
                                        style: AppStyle.subtitle,
                                      ),
                                    ),
                                    SizedBox(
                                      width: Get.width * .2,
                                      child: SizedBox(
                                        height: 60,
                                        child: TextFormField(
                                          obscureText: true,
                                          keyboardType: TextInputType.number,
                                          style: const TextStyle(
                                              color: AppColor.primaryColor,
                                              fontFamily: 'digital-counter-7'),
                                          maxLength: 3,
                                          controller:
                                              controller.cvvCodeController,
                                          decoration: const InputDecoration(
                                              // labelText: 'CVV Code',
                                              ),
                                          validator: (value) {
                                            if (value!.isEmpty &&
                                                value.length != 3) {
                                              return 'Please enter the CVV code'
                                                  .tr;
                                            }
                                            return null;
                                          },
                                        ),
                                      ),
                                    ),
                                  ],
                                )
                              ],
                            ),
                          ),
                        ],
                      ),
                      // const SizedBox(
                      //   height: 20,
                      // ),
                      MyElevatedButton(
                        title: 'Save'.tr,
                        onPressed: () {
                          if (controller.formKey.currentState!.validate()) {
                            // final creditCard = CreditCardModel(
                            //   cardNumber: controller.cardNumberController.text,
                            //   cardHolderName:
                            //       controller.cardHolderNameController.text,
                            //   expiryDate: controller.expiryDateController.text,
                            //   cvvCode: controller.cvvCodeController.text,
                            // );
                            // Process the credit card details
                            // You can use GetX to handle the logic here

                            if (controller.formKey.currentState!.validate()) {
                              SecureStorage().saveData(BoxName.cardNumber,
                                  controller.cardNumberController.text);
                              SecureStorage().saveData(BoxName.cardHolderName,
                                  controller.cardHolderNameController.text);
                              SecureStorage().saveData(BoxName.cvvCode,
                                  controller.cvvCodeController.text);
                              SecureStorage().saveData(BoxName.expiryDate,
                                  controller.expiryDateController.text);
                            }
                          }
                        },
                      ),
                    ],
                  ),
                ))));
  }

  Widget getCardIcon(String cardNumber) {
    String cardType = detectCardType(
        cardNumber); // Function to detect card type based on the first digit

    IconData iconData;
    Color iconColor;

    switch (cardType) {
      case 'Visa':
        iconData = Icons.credit_card_rounded;
        iconColor = Colors.blue; // Change color for Visa cards
        break;
      case 'Mastercard':
        iconData = Icons.credit_card_rounded;
        iconColor = Colors.red; // Change color for Mastercard cards
        break;
      default:
        iconData = Icons.credit_card_rounded;
        iconColor = Colors.black; // Default color for other card types
        break;
    }

    return Icon(
      iconData,
      color: iconColor,
    );
  }

  String detectCardType(String cardNumber) {
    if (cardNumber.startsWith('4')) {
      return 'Visa';
    } else if (cardNumber.startsWith('5')) {
      return 'Mastercard';
    } else {
      return 'Other';
    }
  }
}
