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 UpdateEmergencyContactDialog extends StatefulWidget {
  UpdateEmergencyContactDialog({super.key});

  @override
  State<UpdateEmergencyContactDialog> createState() => _UpdateEmergencyContactDialogState();
}

class _UpdateEmergencyContactDialogState extends State<UpdateEmergencyContactDialog> {
  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 emergency contact error
      viewModel.clearEmergencyContactError();

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

    super.initState();
  }

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

    // Clear emergency contact error when closing
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        profileSettingsViewModel?.clearEmergencyContactError();
      }
    });

    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.enterNewNewContactNumber.tr().toText16(textAlign: TextAlign.start, isBold: true),
          SizedBox(height: 12.h),
          Consumer<ProfileSettingsViewModel>(
            builder: (context, viewModel, child) {
              return TextInputWidget(
                labelText: LocaleKeys.emrgNo.tr(),
                hintText: "05xxxxxxxx",
                controller: textController,
                focusNode: _textFieldFocusNode,
                autoFocus: true,
                padding: EdgeInsets.all(8.h),
                keyboardType: TextInputType.number,
                isEnable: true,
                isReadOnly: false,
                prefix: null,
                isBorderAllowed: true,
                isAllowLeadingIcon: true,
                fontSize: 14.f,
                isCountryDropDown: false,
                leadingIcon: AppAssets.call_fill,
                fontFamily: "Poppins",
                hasError: viewModel.emergencyContactError != null,
                errorMessage: viewModel.emergencyContactError,
                onChange: (value) {
                  // Clear error when user starts typing
                  viewModel.clearEmergencyContactError();
                },
              );
            },
          ),
          SizedBox(height: 12.h),
          CustomButton(
            text: LocaleKeys.submit.tr(context: context),
            onPressed: () {
              // Unfocus keyboard
              _textFieldFocusNode.unfocus();
              FocusScope.of(context).unfocus();

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

              LoaderBottomSheet.showLoader(loadingText: LocaleKeys.loadingText.tr(context: context));
              profileSettingsViewModel!.updatePatientInfo(
                patientInfo: {
                  "PreferredLanguage": profileSettingsViewModel!.getPatientInfoForUpdate!.preferredLanguage,
                  "EmailAddress": profileSettingsViewModel!.getPatientInfoForUpdate!.emailAddress,
                  "EmergencyContactName": profileSettingsViewModel!.getPatientInfoForUpdate!.emergencyContactName,
                  "EmergencyContactNo": textController!.text,
                  "IsEmailAlertRequired": true,
                  "IsSMSAlertRequired": true,
                },
                onSuccess: (response) {
                  LoaderBottomSheet.hideLoader();
                  profileSettingsViewModel!.clearEmergencyContactError();
                  final navContext = getIt.get<NavigationService>().navigatorKey.currentContext;
                  if (navContext == null) return;
                  showCommonBottomSheetWithoutHeight(navContext, title: LocaleKeys.success.tr(context: navContext), child: Utils.getSuccessWidget(loadingText: LocaleKeys.success.tr()),
                      callBackFunc: () async {
                    Navigator.of(navContext).pop();
                    profileSettingsViewModel!.getProfileSettings();
                  }, isFullScreen: false, isAutoDismiss: true);
                },
                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),
          ),
        ],
      ),
    );
  }
}
