import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/enums.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/authentication/login.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/app_bar_widget.dart';
import 'package:hmg_patient_app_new/widgets/bottomsheet/generic_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';

class SavedLogin extends StatefulWidget {
  // final SelectDeviceIMEIRES savedLoginData;

  // const SavedLogin(this.savedLoginData, {Key? key}) : super(key: key);
  const SavedLogin();

  @override
  _SavedLogin createState() => _SavedLogin();
}

class _SavedLogin extends State<SavedLogin> {
  LoginTypeEnum loginType = LoginTypeEnum.sms;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        onBackPressed: () {},
        onLanguageChanged: (lang) {},
      ),
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 24.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const Spacer(flex: 2),
              // Welcome back text
              LocaleKeys.welcomeBack.tr().toText16(color: AppColors.inputLabelTextColor),
              SizedBox(height: 16.h),
              ("widget.savedLoginData.name!.toLowerCase().capitalizeFirstofEach").toText26(isBold: true, height: 26 / 36, color: AppColors.textColor),
              SizedBox(height: 24.h),
              Container(
                padding: EdgeInsets.all(16.h),
                decoration: BoxDecoration(
                  color: AppColors.whiteColor,
                  border: Border.all(color: AppColors.whiteColor),
                  borderRadius: BorderRadius.circular(24.h),
                  boxShadow: [
                    BoxShadow(color: Color(0x0D000000), blurRadius: 16, offset: Offset(0, 0), spreadRadius: 5),
                  ],
                ),
                child: Column(
                  children: [
                    // Last login info
                    ('LocaleKeys.lastloginBy.tr()' + ' {getType(widget.savedLoginData.logInType!, context)}').toText14(isBold: true, color: AppColors.greyTextColor),
                    ('widget.savedLoginData.createdOn != null ? DateUtil.getFormattedDate(DateUtil.convertStringToDate(widget.savedLoginData.createdOn!), "d MMMM, y at HH:mm") : --')
                        .toText16(isBold: true, color: AppColors.textColor),

                    Container(margin: EdgeInsets.all(16.h), child: Utils.buildSvgWithAssets(icon: getTypeIcons(loginType.toInt), iconColor: loginType.toInt == 4 ? null : AppColors.primaryRedColor)),
                    // Face ID login button
                    Container(
                      height: 45,
                      child: CustomButton(
                        text: "${LocaleKeys.loginBy.tr()} ${loginType.displayName}",
                        onPressed: () {
                          if (loginType == LoginTypeEnum.fingerprint || loginType == LoginTypeEnum.face) {
                            // loginWithFingerPrintFace(loginType.toInt, widget.savedLoginData.iMEI!);
                          } else {
                            int? val = loginType.toInt;
                            //checkUserAuthentication(val);
                          }
                        },
                        backgroundColor: Color(0xffED1C2B),
                        borderColor: Color(0xffFEE9EA),
                        textColor: Colors.white,
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                        borderRadius: 12,
                        padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
                        icon: AppAssets.apple_finder,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 24),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  LocaleKeys.oR.tr(),
                  style: context.dynamicTextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                ),
              ),
              const SizedBox(height: 24),
              // OTP login button
              loginType != null && loginType.toInt != 1
                  ? Column(
                      children: [
                        loginType.toInt != 1
                            ? CustomButton(
                                text: LocaleKeys.loginByOTP.tr(),
                                onPressed: () {
                                  showModalBottomSheet(
                                    context: context,
                                    isScrollControlled: true,
                                    isDismissible: false,
                                    useSafeArea: true,
                                    backgroundColor: Colors.transparent,
                                    enableDrag: false,
                                    // Prevent dragging to avoid focus conflicts
                                    builder: (bottomSheetContext) => StatefulBuilder(builder: (BuildContext context, StateSetter setModalState) {
                                      return Padding(
                                        padding: EdgeInsets.only(bottom: MediaQuery.of(bottomSheetContext).viewInsets.bottom),
                                        child: SingleChildScrollView(
                                          child: GenericBottomSheet(
                                            countryCode: "966",
                                            initialPhoneNumber: "",
                                            textController: TextEditingController(),
                                            isFromSavedLogin: true,
                                            isEnableCountryDropdown: true,
                                            onCountryChange: (value) {},
                                            onChange: (String? value) {},
                                            buttons: [
                                              Padding(
                                                padding: EdgeInsets.only(bottom: 10.h),
                                                child: CustomButton(
                                                  text: LocaleKeys.sendOTPSMS.tr(),
                                                  onPressed: () {
                                                    Navigator.of(context).pop();
                                                    loginType = LoginTypeEnum.sms;
                                                    int? val = loginType.toInt;
                                                    // checkUserAuthentication(val);
                                                  },
                                                  backgroundColor: AppColors.primaryRedColor,
                                                  borderColor: AppColors.primaryRedBorderColor,
                                                  textColor: AppColors.whiteColor,
                                                  icon: AppAssets.message,
                                                ),
                                              ),
                                              Row(
                                                crossAxisAlignment: CrossAxisAlignment.center,
                                                mainAxisAlignment: MainAxisAlignment.center,
                                                children: [
                                                  Padding(padding: EdgeInsets.symmetric(horizontal: 8.h), child: (LocaleKeys.oR.tr()).toText16(color: AppColors.textColor)),
                                                ],
                                              ),
                                              Padding(
                                                padding: const EdgeInsets.only(bottom: 10, top: 10),
                                                child: CustomButton(
                                                  text: LocaleKeys.sendOTPWHATSAPP.tr(),
                                                  onPressed: () {
                                                    Navigator.of(context).pop();
                                                    loginType = LoginTypeEnum.whatsapp;
                                                    int? val = loginType.toInt;
                                                    // checkUserAuthentication(val);
                                                  },
                                                  backgroundColor: AppColors.transparent,
                                                  borderColor: AppColors.textColor,
                                                  textColor: AppColors.textColor,
                                                  icon: AppAssets.whatsapp,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      );
                                    }),
                                  );
                                },
                                backgroundColor: AppColors.whiteColor,
                                borderColor: AppColors.borderOnlyColor,
                                textColor: AppColors.textColor,
                                borderWidth: 2,
                                padding: EdgeInsets.fromLTRB(0, 14, 0, 14),
                                icon: AppAssets.password_validation,
                              )
                            : Container(),
                        SizedBox(
                          height: 20,
                        ),
                      ],
                    )
                  : CustomButton(
                      text: "${LocaleKeys.loginBy.tr()} ${LoginTypeEnum.whatsapp.displayName}",
                      onPressed: () {
                        if (loginType == LoginTypeEnum.fingerprint || loginType == LoginTypeEnum.face) {
                          // loginWithFingerPrintFace(loginType.toInt, "iMEI");
                        } else {
                          loginType = LoginTypeEnum.whatsapp;
                          int? val = loginType.toInt;
                          // checkUserAuthentication(val);
                        }
                      },
                      backgroundColor: AppColors.whiteColor,
                      borderColor: Color(0xFF2E3039),
                      textColor: Color(0xFF2E3039),
                      borderWidth: 2,
                      padding: EdgeInsets.fromLTRB(0, 14, 0, 14),
                      icon: AppAssets.whatsapp,
                    ),
              const Spacer(flex: 2),
              // OR divider

              const SizedBox(height: 24),
              // Guest and Switch account
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Container(
                      height: 56,
                      child: CustomButton(
                        text: LocaleKeys.guest.tr(),
                        onPressed: () {
                          Navigator.of(context).pushReplacement(
                            MaterialPageRoute(builder: (BuildContext context) => LoginScreen()),
                          );
                        },
                        backgroundColor: Color(0xffFEE9EA),
                        borderColor: Color(0xffFEE9EA),
                        textColor: Color(0xffED1C2B),
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                        borderRadius: 12,
                        padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
                        // icon: "assets/images/svg/apple-finder.svg",
                      ),
                    ),
                  ),
                  SizedBox(
                    width: MediaQuery.of(context).size.width * 0.05,
                  ),
                  Expanded(
                    child: Container(
                      height: 56,
                      child: CustomButton(
                        text: LocaleKeys.switchAccount.tr(),
                        onPressed: () {
                          Navigator.of(context).pushReplacement(
                            MaterialPageRoute(builder: (BuildContext context) => LoginScreen()),
                          );
                        },
                        backgroundColor: Color(0xffFEE9EA),
                        borderColor: Color(0xffFEE9EA),
                        textColor: Color(0xffED1C2B),
                        fontSize: 15,
                        fontWeight: FontWeight.w500,
                        borderRadius: 12,
                        padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
                        // icon: "assets/images/svg/apple-finder.svg",
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 20),
            ],
          ),
        ),
      ),
    );
  }

  String getTypeIcons(int type) {
    final types = {
      1: AppAssets.sms,
      2: AppAssets.fingerprint,
      3: AppAssets.fingerprint,
      4: AppAssets.whatsapp,
    };

    if (types.containsKey(type)) {
      return types[type]!;
    } else {
      throw Exception('Invalid login type: $type');
    }
  }
}
