import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_custom_clippers/flutter_custom_clippers.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:uco_mobile_poc/app/modules/login/views/shared/login_widget.dart';

// import 'package:url_launcher/url_launcher.dart';
import '../../../core/constants/app_assets.dart';
import '../../../core/constants/form_field_constants.dart';
import '../../../core/constants/translation_keys.dart';
import '../../../core/data/data_source_auth/remote_data_source/app_remote_data_source.dart';
import '../../../core/data/repositories/app_repositories.dart';
import '../../../core/utils/SessionCache.dart';
import '../../../core/utils/fields_utils.dart';
import '../../../custom_widgets/Fields/input_field.dart';
import '../../../custom_widgets/custom_button.dart';
import '../../../custom_widgets/custom_label.dart';
import '../../../custom_widgets/custom_toasty.dart';
import '../../../res/app_colors.dart';
import '../../../routes/app_pages.dart';
import '../controllers/login_screen_controller.dart';

class LoginScreenView extends GetView<LoginScreenController> {
  const LoginScreenView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    controller.context = context;
    Get.lazyPut(() => AppRemoteDataSource());
    Get.lazyPut<AppRepositories>(() => AppRepositoriesImpl(remoteDataSource: Get.find<AppRemoteDataSource>()));
    print("Width login  ${MediaQuery.sizeOf(context).width} ");

    print("Height login ${MediaQuery.sizeOf(context).height} ");

    String className = runtimeType.toString().split('.').last;
    return SafeArea(
      child: Scaffold(
          persistentFooterButtons: [
            BottomNavigationBar(
              backgroundColor: AppColors.colorSecondary.withOpacity(0.1),
              elevation: 0,
              type: BottomNavigationBarType.fixed,
              items: [
                //
                BottomNavigationBarItem(
                  icon: LoginWidgets.bottomTabs(context, TranslationKeys.makeTranslation(TranslationKeys.textFindUAgent), AppAssets.ic_security, () {
                    Toasty.success("Coming Soon.....");
                    // Get.toNamed(Routes.O_T_P_SCREEN);
                    // LoginWidgets.showBottomSheet(context, BottomSheetLogin.options, (index) {
                    //   BottomSheetLogin option = BottomSheetLogin.options[index];
                    //   if (option.description == TranslationKeys.makeTranslation(TranslationKeys.textLogin)) {}
                    // });
                  }, context.textTheme.bodySmall!.copyWith(fontSize: 12)),
                  label: '',
                ),
                BottomNavigationBarItem(
                  icon: LoginWidgets.bottomTabs(
                      context,
                      TranslationKeys.makeTranslation(
                          TranslationKeys.textQRPay),
                      AppAssets.ic_QR,
                      () {
                        Get.toNamed(Routes.qrViewScreen);
                      },
                      context.textTheme.bodySmall!.copyWith(fontSize: 12)),
                  label: '',
                ),
                BottomNavigationBarItem(
                  icon: LoginWidgets.bottomTabs(context, TranslationKeys.makeTranslation(TranslationKeys.textHelp), AppAssets.ic_client, () {
                    Get.toNamed(Routes.faqsViews);
                    // showModalBottomSheetWidget(Get.context!);

                    // Toasty.success("Coming Soon.....");
                  }, context.textTheme.bodySmall!.copyWith(fontSize: 12)),
                  label: '',
                ),
                BottomNavigationBarItem(
                  icon: LoginWidgets.bottomTabs(context, TranslationKeys.makeTranslation(TranslationKeys.textContactUs), AppAssets.ic_contact_us, () {
                    showBottomSheet(context);
                  }, context.textTheme.bodySmall!.copyWith(fontSize: 12)),
                  label: '',
                ),
              ],
            ),
          ],
          body: SingleChildScrollView(
            child: Column(
              children: [
                GestureDetector(
                  onTap: () {
                    showCurrencyDialog(context);
                  },
                  child: Align(
                    alignment: Alignment.centerRight,
                    child: Padding(
                      padding: const EdgeInsets.only(right: 8.0, left: 8.0),
                      child: Container(
                        decoration: const BoxDecoration(color: AppColors.colorPrimary, borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20))),
                        height: 60,
                        width: 30,
                        child: Padding(
                          padding: const EdgeInsets.only(top: 28.0, left: 5, right: 5),
                          child: SvgPicture.asset(AppAssets.ic_arrow_down, height: 10, width: 10),
                        ),
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Center(
                        child: Image.asset("assets/uco/logo/ic_launcher.png", height: 90, width: 130,/* fit: BoxFit.cover*/),
                      ),
                      const SizedBox(height: 20),
                      controller.userNameInputField = InputField(
                        enableInteractiveSelection: false,
                        refKey: FormFieldConstants.instance().getFormKey("${className}userNameField"),
                        controller: FormFieldConstants.instance().getController("${className}userNameField"),
                        hintText: "Enter Email",
                        labelText: "Email*",
                        inputFormatters: [LengthLimitingTextInputFormatter(FieldUtils.userNameFieldLength)],
                        keyboardType: TextInputType.emailAddress,
                      ),
                      controller.passwordInputField = InputField(
                        enableInteractiveSelection: false,
                        refKey: FormFieldConstants.instance().getFormKey("${className}passwordField"),
                        controller: FormFieldConstants.instance().getController("${className}passwordField"),
                        hintText: "Enter Password",
                        labelText: "Password*",
                        keyboardType: TextInputType.visiblePassword,
                        requiredPasswordIcon: true,
                        isPassword: true,
                        onSubmitted: (value) {
                          controller.validateAndLogin();
                        },
                      ),
                      const SizedBox(height: 20),
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 100),
                        child: CustomButton(
                          onPressed: () {
                            controller.validateAndLogin();
                          },
                          buttonPadding: const EdgeInsets.symmetric(vertical: 8),
                          buttonText: TranslationKeys.makeTranslation(TranslationKeys.textLogin),
                          buttonColor: AppColors.colorButton,
                          textStyle: const TextStyle(color: AppColors.white),
                        ),
                      ),
                      const SizedBox(height: 10),
                      GestureDetector(
                        onTap: () {
                          Get.toNamed(Routes.SIGN_UP_SCREEN_STEP1);
                        },
                        child: Text.rich(
                          TextSpan(
                            text: TranslationKeys.makeTranslation(TranslationKeys.textNotRegisterUser), // First part of the text
                            style: Theme.of(context).textTheme.bodySmall,
                            children: <InlineSpan>[
                              const WidgetSpan(
                                child: SizedBox(width: 8.0), // Adjust the width as needed for the space
                              ),
                              TextSpan(
                                text: TranslationKeys.makeTranslation(TranslationKeys.textRegisterNow),
                                style: Theme.of(context).textTheme.bodySmall?.copyWith(color: AppColors.colorDialogBG, fontWeight: FontWeight.w400),
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(height: 30),
                      Obx(() {
                        return Visibility(
                          visible: SessionCache.instance.fingerPrintController.isFingerprintSupported.value && SessionCache.instance.fingerPrintController.isFingerPrintExistInDB.value,
                          child: Center(
                            child: SizedBox(
                              width: 65,
                              height: 65,
                              child: Material(
                                child: InkWell(
                                  onTap: () {
                                    controller.loginUsingFingerPrint = true;
                                    controller.fingerPrintLogin();
                                  },
                                  customBorder: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(100), // Set the border radius
                                  ),
                                  child: Container(
                                    decoration: BoxDecoration(color: AppColors.colorGrey800.withOpacity(0.50), borderRadius: const BorderRadius.all(Radius.circular(100))),
                                    child: const Column(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Expanded(
                                          child: Icon(
                                            color: AppColors.colorButton,
                                            Icons.fingerprint_sharp,
                                            size: 35.0,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        );
                      }),
                      // controller.dateField = CustomDateTimePicker(
                      //   refKey: FormFieldConstants.instance()
                      //       .getFormKey("${className}dateField"),
                      //   controller: FormFieldConstants.instance()
                      //       .getController("${className}dateField"),
                      //   labelText: "picker",
                      // ),
                      // SizedBox(height: 10),
                      // controller.genderField = CustomDropDown(
                      //   listData: [DropDown(id: "id1", label: "Label1"), DropDown(id: "id2", label: "Label2"), DropDown(id: "id3", label: "Label3")].obs,
                      //   labelText: "Gender",
                      //   isRequired: true,
                      // ),
                    ],
                  ),
                )
              ],
            ),
          )),
    );
  }

  void showModalBottomSheetWidget(BuildContext context) {
    List<SupportBottomSheet> supportBottomSheetList = <SupportBottomSheet>[
      SupportBottomSheet(
          image: AppAssets.ic_email,
          title: TranslationKeys.makeTranslation(TranslationKeys.textEmail),
          onTap: () {
            // launch("mailto:info@mfsys.com.pk");
          }),
      SupportBottomSheet(
          image: AppAssets.ic_phone,
          title: TranslationKeys.makeTranslation(TranslationKeys.textPhone),
          onTap: () async {
            // launch("tel:021213123123");
          }),
    ];
    showModalBottomSheet<void>(
      context: context,
      useRootNavigator: true,
      backgroundColor: Colors.transparent,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10))),
      builder: (BuildContext context) {
        return responsiveWidget(
          Stack(
            children: [
              Align(
                alignment: Alignment.bottomCenter,
                child: Container(
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    //border: Border.all(color: Colors.grey, width: 1),
                    borderRadius: BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10)),
                  ),
                  margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 0),
                  padding: const EdgeInsets.only(top: 12),
                  child: ListView(
                    physics: const NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    children: [
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              TranslationKeys.makeTranslation(TranslationKeys.textGetInTouch),
                              style: Theme.of(context).textTheme.titleSmall,
                            ),
                            InkWell(
                              onTap: () {
                                Navigator.pop(context);
                              },
                              child: SvgPicture.asset(AppAssets.ic_cross, height: 15, width: 15),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.all(10),
                        child: GridView.builder(
                          itemCount: supportBottomSheetList.length,
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2,
                            crossAxisSpacing: 15,
                            mainAxisSpacing: 15,
                          ),
                          itemBuilder: (context, index) {
                            return InkWell(
                              customBorder: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10),
                              ),
                              onTap: supportBottomSheetList[index].onTap,
                              child: Container(
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  border: Border.all(color: Colors.grey, width: 1),
                                  borderRadius: const BorderRadius.all(Radius.circular(10)),
                                ),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    SvgPicture.asset(
                                      "${supportBottomSheetList[index].image}",
                                    ),
                                    const SizedBox(height: 20),
                                    Center(
                                      child: LabelText("${supportBottomSheetList[index].title}"),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// Contact Us Bottom Sheet Widget
  showBottomSheet(BuildContext context) {
    List<SupportBottomSheet> supportBottomSheetList = <SupportBottomSheet>[
      SupportBottomSheet(
          image: AppAssets.ic_email,
          title: TranslationKeys.makeTranslation(TranslationKeys.textEmail),
          onTap: () {
            // launch("mailto:info@mfsys.com.pk");
          }),
      SupportBottomSheet(
          image: AppAssets.ic_phone,
          title: TranslationKeys.makeTranslation(TranslationKeys.textPhone),
          onTap: () async {
            // launch("tel:021213123123");
          }),
    ];

    showModalBottomSheet<void>(
      context: context,
      backgroundColor: Colors.transparent,
      anchorPoint: Offset.zero,
      builder: (BuildContext context) {
        return responsiveWidget(
            Container(height: 25,width: 30, color: Colors.red, child: Text("data"),clipBehavior: Clip.none,),);
      },
    );

    showModalBottomSheet(
      context: context,
      builder: (context) =>
          contactUsBottomSheet(context, supportBottomSheetList),
    );

    Get.bottomSheet(
      contactUsBottomSheet(context, supportBottomSheetList),
      useRootNavigator: true,
      backgroundColor: Colors.transparent,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10))),
    );
  }

  Widget contactUsBottomSheet(BuildContext context, List<SupportBottomSheet> supportBottomSheetList) {
    return responsiveWidget(
      Stack(
        fit: StackFit.loose,
        children: [
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(color: Colors.grey, width: 1),
                borderRadius: const BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10)),
              ),
              margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 0),
              child: ListView(
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          TranslationKeys.makeTranslation(TranslationKeys.textGetInTouch),
                          style: Theme.of(context).textTheme.titleSmall,
                        ),
                        InkWell(
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: SvgPicture.asset(
                            AppAssets.ic_cross,
                            height: 15,
                            width: 15,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.all(10),
                    margin: const EdgeInsets.only(bottom: 20),
                    child: GridView.builder(
                      itemCount: supportBottomSheetList.length,
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        crossAxisSpacing: 15,
                        mainAxisSpacing: 15,
                      ),
                      itemBuilder: (context, index) {
                        return InkWell(
                          customBorder: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          onTap: supportBottomSheetList[index].onTap,
                          child: Container(
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey, width: 1),
                              borderRadius: const BorderRadius.all(Radius.circular(10)),
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                SvgPicture.asset(
                                  "${supportBottomSheetList[index].image}",
                                  height: 50,
                                  width: 50,
                                ),
                                const SizedBox(height: 20),
                                Center(
                                  child: LabelText(
                                    "${supportBottomSheetList[index].title}",
                                    style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 14),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void showCurrencyDialog(BuildContext loginScreenContext) {
    showGeneralDialog(
      context: loginScreenContext,
      barrierDismissible: true,
      transitionDuration: const Duration(milliseconds: 500),
      barrierLabel: MaterialLocalizations.of(loginScreenContext).dialogLabel,
      barrierColor: Colors.black.withOpacity(0.5),
      pageBuilder: (context, _, __) {
        return responsiveWidget(
          Stack(
            children: <Widget>[
              Positioned(
                top: 200,
                right: 0,
                child: GestureDetector(
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: Align(
                    alignment: Alignment.centerRight,
                    child: Padding(
                      padding: const EdgeInsets.only(right: 5.0, left: 8.0),
                      child: Container(
                        decoration: const BoxDecoration(color: AppColors.colorPrimary, borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20))),
                        height: 70,
                        width: 30,
                        child: Padding(
                          padding: const EdgeInsets.only(top: 28.0, left: 5, right: 5),
                          child: SvgPicture.asset(
                            AppAssets.ic_arrow_down,
                            height: 10,
                            width: 10,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              Align(
                alignment: Alignment.topCenter,
                child: ClipPath(
                  clipper: MultipleRoundedCurveClipper(),
                  child: Card(
                    elevation: 2.0,
                    child: ListView(
                      shrinkWrap: true,
                      children: <Widget>[
                        Image.asset(
                          AppAssets.uc_logo,
                          height: 55,
                          width: 130,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Padding(
                              padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(TranslationKeys.makeTranslation(TranslationKeys.textUPrimary), style: Theme.of(context).textTheme.titleSmall),
                                  const SizedBox(height: 5),
                                  Text(TranslationKeys.makeTranslation(TranslationKeys.textUCash), style: Theme.of(context).textTheme.titleSmall),
                                  const SizedBox(height: 5),
                                  Text(TranslationKeys.makeTranslation(TranslationKeys.textUSave), style: Theme.of(context).textTheme.titleSmall),
                                  const SizedBox(height: 5),
                                  Text(TranslationKeys.makeTranslation(TranslationKeys.textUChaChing), style: Theme.of(context).textTheme.titleSmall),
                                ],
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Text("\$1,800.00", style: Theme.of(context).textTheme.titleSmall),
                                  const SizedBox(height: 5),
                                  Text("\$500.00", style: Theme.of(context).textTheme.titleSmall),
                                  const SizedBox(height: 5),
                                  Text("\$1288.06", style: Theme.of(context).textTheme.titleSmall),
                                  const SizedBox(height: 5),
                                  Text("\$120,000.00", style: Theme.of(context).textTheme.titleSmall),
                                  const SizedBox(
                                    height: 20,
                                  )
                                ],
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
      transitionBuilder: (context, animation, secondaryAnimation, child) {
        return SlideTransition(
          position: CurvedAnimation(
            parent: animation,
            curve: Curves.easeOut,
          ).drive(Tween<Offset>(
            begin: const Offset(0, -1.0),
            end: Offset.zero,
          )),
          child: child,
        );
      },
    );
  }
}

class SupportBottomSheet {
  String? image;
  String? title;
  Function()? onTap;

  SupportBottomSheet({this.image, this.title, this.onTap});
}
