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_export.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/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/water_monitor/water_monitor_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/services/dialog_service.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.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:provider/provider.dart';

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

  @override
  State<WaterMonitorSettingsPage> createState() => _WaterMonitorSettingsPageState();
}

class _WaterMonitorSettingsPageState extends State<WaterMonitorSettingsPage> {
  late DialogService dialogService;

  @override
  void initState() {
    super.initState();
    dialogService = getIt.get<DialogService>();
  }

  // No need to call initialize() here since it's already called in water_consumption_screen
  // The ViewModel is shared via Provider, so data is already loaded

  // Reusable method to build selection row widget
  Widget _buildSelectionRow({
    required String value,
    required String groupValue,
    required VoidCallback onTap,
    bool useUpperCase = false,
  }) {
    return SizedBox(
      height: 70.h,
      child: Row(
        spacing: 8.h,
        children: [
          Radio<String>(
            value: value,
            groupValue: groupValue,
            activeColor: AppColors.errorColor,
            onChanged: (_) => onTap(),
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          ),
          (useUpperCase ? value.toUpperCase() : value.toCamelCase).toText16(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).expanded,
        ],
      ).onPress(onTap),
    );
  }

  // Reusable method to show selection bottom sheet
  void _showSelectionBottomSheet({
    required BuildContext context,
    required String title,
    required List<String> items,
    required String selectedValue,
    required Function(String) onSelected,
    bool useUpperCase = false,
  }) {
    dialogService.showFamilyBottomSheetWithoutHWithChild(
      label: title,
      message: "",
      child: Container(
        padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h),
        decoration: BoxDecoration(color: AppColors.whiteColor, borderRadius: BorderRadius.circular(20.r)),
        child: ListView.separated(
          shrinkWrap: true,
          itemCount: items.length,
          itemBuilder: (context, index) {
            final item = items[index];
            return _buildSelectionRow(
              value: item,
              groupValue: selectedValue,
              useUpperCase: useUpperCase,
              onTap: () {
                onSelected(item);
                Navigator.pop(context);
              },
            );
          },
          separatorBuilder: (_, __) => Divider(height: 1, color: AppColors.dividerColor),
        ),
      ),
      onOkPressed: () {},
    );
  }

  void _showGenderSelectionBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) {
    _showSelectionBottomSheet(
      context: context,
      title: LocaleKeys.selectGender.tr(context: context),
      items: viewModel.genderOptions,
      selectedValue: viewModel.selectedGenderDisplay,
      onSelected: viewModel.setGender,
    );
  }

  void _showHeightUnitSelectionBottomSheet(BuildContext context, WaterMonitorViewModel viewModel) {
    _showSelectionBottomSheet(
      context: context,
      title: LocaleKeys.selectUnit.tr(context: context),
      items: viewModel.getHeightUnitsList(),
      selectedValue: viewModel.selectedHeightUnitDisplay,
      onSelected: viewModel.setHeightUnit,
      useUpperCase: true,
    );
  }

  void _showWeightUnitSelectionBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) {
    _showSelectionBottomSheet(
      context: context,
      title: LocaleKeys.selectUnit.tr(context: context),
      items: viewModel.getWeightUnitsList(),
      selectedValue: viewModel.selectedWeightUnitDisplay,
      onSelected: viewModel.setWeightUnit,
      useUpperCase: true,
    );
  }

  void _showActivityLevelSelectionBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) {
    _showSelectionBottomSheet(
      context: context,
      title: LocaleKeys.selectActivityLevel.tr(context: context),
      items: viewModel.activityLevels,
      selectedValue: viewModel.selectedActivityLevelDisplay,
      onSelected: viewModel.setActivityLevel,
    );
  }

  void _showNumberOfRemindersSelectionBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) {
    _showSelectionBottomSheet(
      context: context,
      title: LocaleKeys.selectNumberOfReminders.tr(context: context),
      items: viewModel.reminderOptions,
      selectedValue: viewModel.selectedNumberOfRemindersDisplay,
      onSelected: viewModel.setNumberOfReminders,
    );
  }

  // Reusable method to build text field
  Widget _buildTextField(TextEditingController controller, String hintText, {TextInputType keyboardType = TextInputType.name}) {
    return TextField(
      controller: controller,
      keyboardType: keyboardType,
      maxLines: 1,
      cursorHeight: 14.h,
      textAlignVertical: TextAlignVertical.center,
      decoration: InputDecoration(
        border: InputBorder.none,
        contentPadding: EdgeInsets.zero,
        isCollapsed: true,
        hintText: hintText,
        hintStyle: const TextStyle(color: Colors.grey),
      ),
      style: TextStyle(
        fontSize: 14.f,
        fontWeight: FontWeight.w600,
        color: AppColors.textColor,
      ),
    );
  }

  // Reusable method to build settings row
  Widget _buildSettingsRow({
    required String icon,
    required String label,
    String? value,
    Widget? inputField,
    String? unit,
    VoidCallback? onUnitTap,
    VoidCallback? onRowTap,
    bool showDivider = true,
  }) {
    AppState appState = getIt<AppState>();
    return Column(
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              height: 40.w,
              width: 40.w,
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.greyColor,
                borderRadius: 10.r,
                hasShadow: false,
              ),
              child: Center(child: Utils.buildSvgWithAssets(icon: icon, height: 22.w, width: 22.w)),
            ),
            SizedBox(width: 12.w),
            Expanded(
              flex: unit != null ? 3 : 1,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  label.toText12(isBold: true, color: AppColors.inputLabelTextColor),
                  if (inputField != null)
                    Container(
                      height: 20.w,
                      alignment: Alignment.centerLeft,
                      child: inputField,
                    )
                  else if (value != null)
                    value.toCamelCase.toText12(isBold: true, color: AppColors.textColor),
                ],
              ),
            ),
            if (unit != null) ...[
              Container(
                width: 1.w,
                height: 30.w,
                color: AppColors.dividerColor,
              ).paddingOnly(right: 10.w),
              Expanded(
                child: Row(
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        appState.isArabic() ? "الوحدة".toText12(isBold: true, color: AppColors.inputLabelTextColor) : "Unit".toText12(isBold: true, color: AppColors.inputLabelTextColor),
                        unit.toText12(isBold: true, color: AppColors.textColor),
                      ],
                    ),
                    SizedBox(width: 12.w),
                    Utils.buildSvgWithAssets(icon: AppAssets.arrow_down)
                  ],
                ).onPress(onUnitTap ?? () {}),
              ),
            ] else if (onRowTap != null) ...[
              Utils.buildSvgWithAssets(icon: AppAssets.arrow_down),
              SizedBox(width: 4.w),
            ],
          ],
        ).paddingSymmetrical(0.w, 16.w).onPress(onRowTap ?? () {}),
        if (showDivider) Divider(height: 1, color: AppColors.dividerColor),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final viewModel = context.watch<WaterMonitorViewModel>();

    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        title: LocaleKeys.h2oSettings.tr(context: context),
        bottomChild: Container(
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
            color: AppColors.whiteColor,
            borderRadius: 24.r,
            hasShadow: true,
          ),
          child: Padding(
            padding: EdgeInsets.all(24.w),
            child: CustomButton(
              text: LocaleKeys.save.tr(context: context),
              onPressed: () async {
                final success = await viewModel.saveSettings();
                if (!success && viewModel.validationError != null) {
                  dialogService.showErrorBottomSheet(
                    message: viewModel.validationError!,
                  );
                } else if (success) {
                  showCommonBottomSheetWithoutHeight(
                    context,
                    child: Utils.getSuccessWidget(
                      loadingText: LocaleKeys.settingsSavedSuccessfully.tr(context: context),
                    ),
                    callBackFunc: () {},
                    isCloseButtonVisible: false,
                    isDismissible: true,
                    isFullScreen: false,
                  );
                }
              },
              borderRadius: 12.r,
              padding: EdgeInsets.symmetric(vertical: 14.h),
            ),
          ),
        ),
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 24.w, vertical: 24.h),
          padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 4.h, bottom: 4.h),
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true),
          child: Column(
            children: [
              _buildSettingsRow(
                icon: AppAssets.profileIcon,
                label: LocaleKeys.yourName.tr(context: context),
                inputField: _buildTextField(viewModel.nameController, 'Guest'),
              ),
              _buildSettingsRow(
                icon: AppAssets.genderIcon,
                label: LocaleKeys.selectGender.tr(context: context),
                value: viewModel.selectedGenderDisplay,
                onRowTap: () => _showGenderSelectionBottomsheet(context, viewModel),
              ),
              _buildSettingsRow(
                icon: AppAssets.calendarGrey,
                label: LocaleKeys.ageYears.tr(context: context),
                inputField: _buildTextField(
                  viewModel.ageController,
                  '20',
                  keyboardType: TextInputType.number,
                ),
              ),
              _buildSettingsRow(
                icon: AppAssets.heightIcon,
                label: LocaleKeys.height.tr(context: context),
                inputField: _buildTextField(
                  viewModel.heightController,
                  '175',
                  keyboardType: TextInputType.number,
                ),
                unit: viewModel.selectedHeightUnitDisplay,
                onUnitTap: () => _showHeightUnitSelectionBottomSheet(context, viewModel),
              ),
              _buildSettingsRow(
                icon: AppAssets.weightScaleIcon,
                label: LocaleKeys.weight.tr(context: context),
                inputField: _buildTextField(
                  viewModel.weightController,
                  '75',
                  keyboardType: TextInputType.number,
                ),
                unit: viewModel.selectedWeightUnitDisplay,
                onUnitTap: () => _showWeightUnitSelectionBottomsheet(context, viewModel),
              ),
              _buildSettingsRow(
                icon: AppAssets.dumbellIcon,
                label: LocaleKeys.activityLevel.tr(context: context),
                value: viewModel.selectedActivityLevelDisplay,
                onRowTap: () => _showActivityLevelSelectionBottomsheet(context, viewModel),
              ),
              _buildSettingsRow(
                icon: AppAssets.notificationIconGrey,
                label: LocaleKeys.numberOfRemindersInADay.tr(context: context),
                value: viewModel.selectedNumberOfRemindersDisplay,
                onRowTap: () => _showNumberOfRemindersSelectionBottomsheet(context, viewModel),
                showDivider: false,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
