import 'dart:ui' as ui;

import 'package:clarity_flutter/clarity_flutter.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/enums.dart';
import 'package:hmg_patient_app_new/core/utils/date_util.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/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.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/presentation/home/navigation_screen.dart';
import 'package:hmg_patient_app_new/services/navigation_service.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';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

class SavedLogin extends StatefulWidget {
  const SavedLogin({super.key});

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

class _SavedLogin extends State<SavedLogin> with RouteAware {
  LoginTypeEnum loginType = LoginTypeEnum.sms;
  late AuthenticationViewModel authVm;
  late AppState appState;
  bool? isOther;
  PageRoute<dynamic>? _pageRoute;

  void _assignSavedLoginData() {
    authVm.phoneNumberController.text = appState.getSelectDeviceByImeiRespModelElement!.mobile!.startsWith("0")
        ? appState.getSelectDeviceByImeiRespModelElement!.mobile!.replaceFirst("0", "")
        : appState.getSelectDeviceByImeiRespModelElement!.mobile!;
    authVm.nationalIdController.text = appState.getSelectDeviceByImeiRespModelElement!.identificationNo!;

    if (isOther == true) {
      authVm.phoneNumberController.text = appState.getSelectDeviceByImeiRespModelElement!.mobile!;
      authVm.selectedCountrySignup = CountryEnum.others;
    }
  }

  @override
  void initState() {
    Clarity.setCurrentScreenName('Last Login Screen');
    authVm = context.read<AuthenticationViewModel>();
    appState = getIt.get<AppState>();
    loginType = LoginTypeExtension.fromValue(appState.getSelectDeviceByImeiRespModelElement!.logInType!)!;

    // Check if this is an "Others" country user
    isOther = appState.getSelectDeviceByImeiRespModelElement!.isOther == true;

    _assignSavedLoginData();

    if (loginType == LoginTypeEnum.fingerprint || loginType == LoginTypeEnum.face) {
      authVm.loginWithFingerPrintFace(() {});
    }
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route is PageRoute && route != _pageRoute) {
      if (_pageRoute != null) {
        getIt.get<NavigationService>().routeObserver.unsubscribe(this);
      }
      _pageRoute = route;
      getIt.get<NavigationService>().routeObserver.subscribe(this, route);
    }
  }

  @override
  void didPopNext() {
    _assignSavedLoginData();
  }

  @override
  void dispose() {
    getIt.get<NavigationService>().routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.scaffoldBgColor,
      appBar: CustomAppBar(
        onBackPressed: () {
          Navigator.of(context).pop();
          authVm.setIsInitialLoginNavigated(true);
        },
        onLanguageChanged: (value) {
          context.setLocale(value == 'en' ? Locale('en', 'US') : Locale('ar', 'SA'));
        },
      ),
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 24.h),
          child: appState.getSelectDeviceByImeiRespModelElement != null
              ? Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const Spacer(flex: 2),
                    // Welcome back text
                    LocaleKeys.welcomeBack.tr().toText16(color: AppColors.inputLabelTextColor),
                    SizedBox(height: 16.h),
                    appState.getSelectDeviceByImeiRespModelElement != null
                        ? appState.getSelectDeviceByImeiRespModelElement!.name!.toCamelCase.toText26(isBold: true, height: 26 / 36, color: AppColors.textColor, isEnglishOnly: true)
                        : SizedBox(),
                    SizedBox(height: 24.h),
                    Container(
                      padding: EdgeInsets.all(16.h),
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 20.h, hasShadow: false, isCustomShadow: [
                        BoxShadow(color: Color(0x0D000000), blurRadius: 16.h, offset: Offset(0, 0), spreadRadius: 5.h),
                      ]),
                      child: Column(
                        children: [
                          // Last login info - show WhatsApp only if isOther AND loginType is SMS
                          ("${LocaleKeys.lastLoginBy.tr()} ${(isOther == true && loginType == LoginTypeEnum.sms) ? LoginTypeEnum.whatsapp.displayName : loginType.displayName}")
                              .toText14(isBold: true, color: AppColors.greyTextColor, letterSpacing: -1),
                          Directionality(
                            textDirection: ui.TextDirection.ltr,
                            child: appState.getSelectDeviceByImeiRespModelElement != null
                                ? (appState.getSelectDeviceByImeiRespModelElement!.createdOn != null
                                        ? DateUtil.getFormattedDate(DateUtil.convertStringToDate(appState.getSelectDeviceByImeiRespModelElement!.createdOn!), "d MMMM, y 'at' HH:mm")
                                        : '--')
                                    .toText16(isBold: true, color: AppColors.textColor, isEnglishOnly: true)
                                : SizedBox(),
                          ),

                          appState.getSelectDeviceByImeiRespModelElement != null
                              ? Container(
                                  margin: EdgeInsets.all(16.h),
                                  child: Utils.buildSvgWithAssets(
                                      icon: (isOther == true && loginType == LoginTypeEnum.sms) ? AppAssets.whatsapp : getTypeIcons(appState.getSelectDeviceByImeiRespModelElement!.logInType!),
                                      height: 54.h,
                                      width: 54.w,
                                      iconColor: (isOther == true && loginType == LoginTypeEnum.sms) || loginType.toInt == 4 ? null : AppColors.primaryRedColor))
                              : SizedBox(),
                          // Main login button - for isOther with SMS, show WhatsApp, otherwise keep original login type
                          CustomButton(
                            text: (isOther == true && loginType == LoginTypeEnum.sms)
                                ? "${LocaleKeys.loginBy.tr()} ${LoginTypeEnum.whatsapp.displayName}"
                                : "${LocaleKeys.loginBy.tr()} ${loginType.displayName}",
                            onPressed: () {
                              if (loginType == LoginTypeEnum.fingerprint || loginType == LoginTypeEnum.face) {
                                authVm.loginWithFingerPrintFace(() {});
                              } else {
                                // For isOther with SMS, use WhatsApp; otherwise use the original login type
                                authVm.checkUserAuthentication(
                                  otpTypeEnum: (isOther == true && loginType == LoginTypeEnum.sms) ? OTPTypeEnum.whatsapp : (loginType == LoginTypeEnum.sms ? OTPTypeEnum.sms : OTPTypeEnum.whatsapp),
                                );
                              }
                            },
                            backgroundColor: AppColors.primaryRedColor,
                            borderColor: AppColors.primaryRedColor,
                            textColor: Colors.white,
                            fontSize: 12.f,
                            fontWeight: FontWeight.w600,
                            borderRadius: 12.r,
                            height: 44.h,
                            padding: EdgeInsets.symmetric(vertical: 10.h),
                            icon: (isOther == true && loginType == LoginTypeEnum.sms) ? AppAssets.whatsapp : getTypeIcons(loginType.toInt),
                            iconColor: (isOther == true && loginType == LoginTypeEnum.sms) || loginType == LoginTypeEnum.whatsapp ? null : Colors.white,
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 24.h),
                    // Hide OR + OTP login options entirely when isOther is true
                    if (isOther != true) ...[
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 16.w),
                        child: Text(
                          LocaleKeys.oR.tr(),
                          style: context.dynamicTextStyle(
                            fontSize: 16.f,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                      SizedBox(height: 24.h),
                      // OTP login button
                      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: appState.getSelectDeviceByImeiRespModelElement!.outSa == true ? "971" : "966",
                                                    // 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;
                                                              authVm.checkUserAuthentication(otpTypeEnum: OTPTypeEnum.sms);
                                                            },
                                                            backgroundColor: AppColors.primaryRedColor,
                                                            borderColor: AppColors.primaryRedColor,
                                                            textColor: Colors.white,
                                                            icon: AppAssets.sms),
                                                      ),
                                                      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: EdgeInsets.only(bottom: 10.h, top: 10.h),
                                                        child: CustomButton(
                                                          text: LocaleKeys.sendOTPWHATSAPP.tr(),
                                                          onPressed: () {
                                                            Navigator.of(context).pop();
                                                            loginType = LoginTypeEnum.whatsapp;
                                                            authVm.checkUserAuthentication(otpTypeEnum: OTPTypeEnum.whatsapp);
                                                          },
                                                          backgroundColor: AppColors.transparent,
                                                          borderColor: AppColors.textColor,
                                                          textColor: AppColors.textColor,
                                                          icon: AppAssets.whatsapp,
                                                          iconColor: null,
                                                          applyThemeColor: false,
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              );
                                            }),
                                          );
                                        },
                                        height: isFoldable ? 56.h : 50.h,
                                        backgroundColor: AppColors.whiteColor,
                                        borderColor: AppColors.borderOnlyColor,
                                        textColor: AppColors.textColor,
                                        borderWidth: 2,
                                        padding: EdgeInsets.fromLTRB(0, 14.h, 0, 14.h),
                                        icon: AppAssets.sms,
                                        iconColor: AppColors.textColor,
                                      )
                                    : Container(),
                                SizedBox(
                                  height: 20.h,
                                ),
                              ],
                            )
                          : CustomButton(
                              text: "${LocaleKeys.loginBy.tr()} ${LoginTypeEnum.whatsapp.displayName}",
                              icon: AppAssets.whatsapp,
                              iconColor: null,
                              onPressed: () {
                                if (loginType == LoginTypeEnum.fingerprint || loginType == LoginTypeEnum.face) {
                                  authVm.loginWithFingerPrintFace(() {});
                                } else {
                                  loginType = LoginTypeEnum.whatsapp;
                                  authVm.checkUserAuthentication(otpTypeEnum: OTPTypeEnum.whatsapp);
                                }
                              },
                              backgroundColor: AppColors.whiteColor,
                              borderColor: AppColors.textColor,
                              textColor: AppColors.textColor,
                              borderWidth: 2.w,
                              padding: EdgeInsets.fromLTRB(0, 14.h, 0, 14.h),
                              applyThemeColor: false,
                            ),
                    ],

                    const Spacer(flex: 2),
                    // OR divider
                    SizedBox(height: 24.h),
                    // Guest and Switch account
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: SizedBox(
                            height: 56.h,
                            child: CustomButton(
                              text: LocaleKeys.guest.tr(),
                              onPressed: () {
                                authVm.setIsInitialLoginNavigated(true);
                                Navigator.pushAndRemoveUntil(
                                    context,
                                    CustomPageRoute(
                                      page: LandingNavigation(),
                                    ),
                                    (r) => false);
                                // Navigator.of(context).pushAndRemoveUntil(
                                //   MaterialPageRoute(builder: (BuildContext context) => LandingNavigation())
                                // );
                              },
                              backgroundColor: Color(0xffFEE9EA),
                              borderColor: Color(0xffFEE9EA),
                              textColor: Color(0xffED1C2B),
                              fontSize: 16.f,
                              fontWeight: FontWeight.w600,
                              borderRadius: 12.r,
                              padding: EdgeInsets.fromLTRB(0, 10.h, 0, 10.h),
                              // icon: "assets/images/svg/apple-finder.svg",
                            ),
                          ),
                        ),
                        SizedBox(
                          width: MediaQuery.of(context).size.width * 0.05,
                        ),
                        Expanded(
                          child: SizedBox(
                            height: 56.h,
                            child: CustomButton(
                              text: LocaleKeys.switchAccount.tr(),
                              onPressed: () async {
                                await authVm.clearDefaultInputValues();
                                Navigator.of(context).push(
                                  MaterialPageRoute(builder: (BuildContext context) => LoginScreen()),
                                );
                              },
                              backgroundColor: Color(0xffFEE9EA),
                              borderColor: Color(0xffFEE9EA),
                              textColor: Color(0xffED1C2B),
                              fontSize: 15.f,
                              fontWeight: FontWeight.w600,
                              borderRadius: 12.r,
                              padding: EdgeInsets.fromLTRB(0, 10.h, 0, 10.h),
                              // icon: "assets/images/svg/apple-finder.svg",
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 20.h),
                  ],
                )
              : SizedBox.shrink(),
        ),
      ),
    );
  }

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

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