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/dependencies.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/features/profile_settings/profile_settings_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.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/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:provider/provider.dart';

class UpdateEmailDialog extends StatefulWidget {
  UpdateEmailDialog({super.key});

  @override
  State<UpdateEmailDialog> createState() => _UpdateEmailDialogState();
}

class _UpdateEmailDialogState extends State<UpdateEmailDialog> {
  late FocusNode _textFieldFocusNode;
  late TextEditingController? textController;
  ProfileSettingsViewModel? profileSettingsViewModel;

  @override
  void initState() {
    _textFieldFocusNode = FocusNode();
    textController = TextEditingController();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      // Get the view model reference
      final viewModel = Provider.of<ProfileSettingsViewModel>(context, listen: false);

      // Clear any previous email error
      viewModel.clearEmailError();

      // Set the text
      setState(() {
        textController!.text = viewModel.getPatientInfoForUpdate!.emailAddress ?? "";
      });
    });

    super.initState();
  }

  @override
  void dispose() {
    _textFieldFocusNode.dispose();

    // Clear email error when closing
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        profileSettingsViewModel?.clearEmailError();
      }
    });

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    profileSettingsViewModel = Provider.of<ProfileSettingsViewModel>(context);
    return GestureDetector(
      onTap: () {
        _textFieldFocusNode.unfocus();
        FocusScope.of(context).unfocus();
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          LocaleKeys.updateEmailAddressTitle.tr().toText16(textAlign: TextAlign.start, isBold: true),
          SizedBox(height: 12.h),
          Consumer<ProfileSettingsViewModel>(
            builder: (context, viewModel, child) {
              return TextInputWidget(
                labelText: LocaleKeys.email.tr(),
                hintText: "demo@gmail.com",
                controller: textController,
                focusNode: _textFieldFocusNode,
                autoFocus: true,
                padding: EdgeInsets.all(8.h),
                keyboardType: TextInputType.emailAddress,
                isEnable: true,
                isReadOnly: false,
                prefix: null,
                isBorderAllowed: true,
                isAllowLeadingIcon: true,
                fontSize: 14.f,
                isCountryDropDown: false,
                leadingIcon: AppAssets.email,
                fontFamily: "Poppins",
                hasError: viewModel.emailError != null,
                errorMessage: viewModel.emailError,
                onChange: (value) {
                  // Clear error when user starts typing
                  viewModel.clearEmailError();
                },
              );
            },
          ),
          SizedBox(height: 12.h),
          CustomButton(
            text: LocaleKeys.submit.tr(context: context),
            onPressed: () {
              // Unfocus keyboard
              _textFieldFocusNode.unfocus();
              FocusScope.of(context).unfocus();

              // Validate email using ViewModel method
              if (!profileSettingsViewModel!.validateEmail(textController!.text)) {
                // Validation failed, error is already set in viewModel and displayed below field
                return;
              }

              LoaderBottomSheet.showLoader(loadingText: LocaleKeys.updatingEmailAddress.tr(context: context));
              profileSettingsViewModel!.updatePatientInfo(
                patientInfo: {
                  "PreferredLanguage": profileSettingsViewModel!.getPatientInfoForUpdate!.preferredLanguage,
                  "EmailAddress": textController!.text,
                  "EmergencyContactName": profileSettingsViewModel!.getPatientInfoForUpdate!.emergencyContactName,
                  "EmergencyContactNo": profileSettingsViewModel!.getPatientInfoForUpdate!.emergencyContactNo,
                  "IsEmailAlertRequired": true,
                  "IsSMSAlertRequired": true,
                },
                onSuccess: (response) {
                  LoaderBottomSheet.hideLoader();
                  profileSettingsViewModel!.clearEmailError();
                  showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.success.tr(context: context), child: Utils.getSuccessWidget(loadingText: LocaleKeys.success.tr()),
                      callBackFunc: () async {
                    Navigator.of(getIt<NavigationService>().navigatorKey.currentContext!).pop();
                    profileSettingsViewModel!.getProfileSettings();
                  }, isFullScreen: false, isAutoDismiss: true, isCloseButtonVisible: false);
                },
                onError: (error) {
                  LoaderBottomSheet.hideLoader();
                  // Show error message
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text(error)),
                  );
                },
              );
            },
            backgroundColor: AppColors.primaryRedColor,
            borderColor: AppColors.primaryRedColor,
            textColor: const Color(0xFFffffff),
          ),
        ],
      ),
    );
  }
}
