import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.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/int_extensions.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/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/loader/bottomsheet_loader.dart';
import 'package:provider/provider.dart';

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

  @override
  State<PreferredLanguageWidget> createState() => _PreferredLanguageWidgetState();
}

class _PreferredLanguageWidgetState extends State<PreferredLanguageWidget> {
  String? selectedValue;
  late ProfileSettingsViewModel profileSettingsViewModel;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {
        selectedValue = profileSettingsViewModel.getPatientInfoForUpdate?.preferredLanguage!;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    profileSettingsViewModel = Provider.of<ProfileSettingsViewModel>(context, listen: false);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      spacing: 24.h,
      children: [
        LocaleKeys.communicationLanguage.tr(context: context).toText14(),
        Container(
          padding: EdgeInsets.only(top: 4, bottom: 4),
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true),
          child: Column(
            children: [
              languageItem("العربية", "1"),
              1.divider,
              languageItem("English", "2"),
            ],
          ),
        ),
        CustomButton(
            text: LocaleKeys.save.tr(context: context),
            onPressed: () {
              LoaderBottomSheet.showLoader(loadingText: LocaleKeys.loadingText.tr(context: context));
              profileSettingsViewModel!.updatePatientInfo(
                patientInfo: {
                  "PreferredLanguage": selectedValue,
                  "EmailAddress": profileSettingsViewModel.getPatientInfoForUpdate!.emailAddress,
                  "EmergencyContactName": profileSettingsViewModel.getPatientInfoForUpdate!.emergencyContactName,
                  "EmergencyContactNo": profileSettingsViewModel.getPatientInfoForUpdate!.emergencyContactNo,
                  "IsEmailAlertRequired": true,
                  "IsSMSAlertRequired": true,
                },
                onSuccess: (response) {
                  LoaderBottomSheet.hideLoader();
                  showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.success.tr(context: context), child: Utils.getSuccessWidget(loadingText: LocaleKeys.success.tr()),
                      callBackFunc: () async {
                    Navigator.of(GetIt.instance<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)),
                  );
                },
              );
            }),
      ],
    );
  }

  Widget languageItem(String title, String _value) {
    return SizedBox(
      height: 72,
      child: Row(
        spacing: 8.h,
        children: [
          Radio(
            value: _value,
            groupValue: selectedValue,
            activeColor: AppColors.errorColor,
            onChanged: (value) {
              setState(() {
                selectedValue = _value;
              });
            },
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          ),
          title.toText16(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1, fontFamily: _value == "1" ? 'CairoArabic' : 'Poppins').expanded,
        ],
      ).paddingOnly(left: 16, right: 16).onPress(() {
        setState(() {
          selectedValue = _value;
        });
      }),
    );
  }
}
