import 'package:flutter/material.dart';

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

import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/functions/digit_obsecur_formate.dart';
import '../../../controller/home/map_passenger_controller.dart';

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

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MapPassengerController>(
        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 Cared'.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 CreditCardWidget(),
                      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 CreditCardWidget extends StatelessWidget {
  const CreditCardWidget({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    Get.put(CreditCardController());
    return GetBuilder<CreditCardController>(
        builder: (controller) => Container(
            height: Get.height * .3,
            width: Get.width * .9,
            decoration: const BoxDecoration(
              color: AppColor.secondaryColor,
              borderRadius: BorderRadius.all(Radius.circular(15)),
              boxShadow: [
                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.spaceAround,
                    children: [
                      SizedBox(
                        child: Row(
                          children: [
                            getCardIcon(controller.cardNumberController
                                .text), // Dynamic credit card icon
                            SizedBox(
                              width: Get.width * .1,
                            ),
                            SizedBox(
                              width: Get.width * .6,
                              height: 70,
                              child: TextFormField(
                                maxLength: 16,
                                keyboardType: TextInputType.number,
                                controller: controller.cardNumberController,
                                style: const TextStyle(
                                    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 * .1,
                          ),
                          SizedBox(
                            width: Get.width * .6,
                            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 * .1,
                                ),
                                SizedBox(
                                  width: Get.width * .2,
                                  child: SizedBox(
                                    height: 60,
                                    child: TextFormField(
                                      keyboardType: TextInputType.datetime,
                                      controller:
                                          controller.expiryDateController,
                                      decoration: const InputDecoration(
                                          labelText: 'Expiry Date'),
                                      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,
                                ),
                                SizedBox(
                                  width: Get.width * .2,
                                  child: SizedBox(
                                    height: 60,
                                    child: TextFormField(
                                      obscureText: true,
                                      keyboardType: TextInputType.number,
                                      style: const TextStyle(
                                          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;
                                      },
                                    ),
                                  ),
                                )
                              ],
                            ),
                          ),
                        ],
                      ),
                      // 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
                      //     }
                      //   },
                      // ),
                    ],
                  ),
                ))));
  }

  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';
    }
  }
}
