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/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/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/health_calculator_view_model.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:provider/provider.dart';

class BloodCholesterolWidget extends StatefulWidget {
  final Function(dynamic result)? onChange;

  const BloodCholesterolWidget({super.key, this.onChange});

  @override
  State<BloodCholesterolWidget> createState() => _BloodCholesterolWidgetState();
}

class _BloodCholesterolWidgetState extends State<BloodCholesterolWidget> {
  final TextEditingController _mgdlController = TextEditingController();
  final TextEditingController _mmolController = TextEditingController();
  final FocusNode _mgdlFocus = FocusNode();
  final FocusNode _mmolFocus = FocusNode();
  bool _isProgrammaticChange = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<HealthCalcualtorViewModel>(
        context,
        listen: false,
      ).clearBloodCholesterol();
    });
  }

  @override
  void dispose() {
    _mgdlController.dispose();
    _mmolController.dispose();
    _mgdlFocus.dispose();
    _mmolFocus.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<HealthCalcualtorViewModel>(
      builder: (context, provider, _) {
        _isProgrammaticChange = true;
        final mgdlText = provider.cholMgdlValue ?? '';
        final mmolText = provider.cholMmolValue ?? '';

        // Only update if focus is not on this field (to avoid cursor jumping)
        if (!_mgdlFocus.hasFocus && _mgdlController.text != mgdlText) {
          _mgdlController.text = mgdlText;
          _mgdlController.selection = TextSelection.fromPosition(
            TextPosition(offset: _mgdlController.text.length),
          );
        }

        if (!_mmolFocus.hasFocus && _mmolController.text != mmolText) {
          _mmolController.text = mmolText;
          _mmolController.selection = TextSelection.fromPosition(
            TextPosition(offset: _mmolController.text.length),
          );
        }

        _isProgrammaticChange = false;

        return Container(
          margin: EdgeInsets.zero,
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true),
          child: Column(
            children: [
              _buildInputField(
                label: LocaleKeys.mldl.tr(),
                hint: "120",
                controller: _mgdlController,
                focusNode: _mgdlFocus,
                onChanged: (value) {
                  if (_isProgrammaticChange) return;
                  provider.onCholesterolMgdlChanged(value);
                },
              ).paddingOnly(top: 16.h),
              Row(
                children: [
                  const Expanded(
                    flex: 3,
                    child: Divider(height: 1, color: Color(0xFFEEEEEE)),
                  ),
                  SizedBox(width: 8.w),
                  Utils.buildSvgWithAssets(
                    icon: AppAssets.switchBtn,
                    width: 40.h,
                    height: 40.h,
                  ).onPress(() {
                    // Unfocus both fields before switching
                    _mgdlFocus.unfocus();
                    _mmolFocus.unfocus();
                    provider.switchBloodCholesterolValues();
                  }),
                ],
              ),
              _buildInputField(
                label: LocaleKeys.mmol.tr(),
                hint: "3.1",
                controller: _mmolController,
                focusNode: _mmolFocus,
                onChanged: (value) {
                  if (_isProgrammaticChange) return;
                  provider.onCholesterolMmolChanged(value);
                },
              ).paddingOnly(bottom: 16.h),
              const Divider(height: 1, color: Color(0xFFEEEEEE)),
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Utils.buildSvgWithAssets(icon: AppAssets.globe, width: 18.w, height: 18.w),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: LocaleKeys.convertBloodcholesterolInfo.tr(context: context).toText12(isBold: true, color: AppColors.inputLabelTextColor),
                  ),
                ],
              ).paddingSymmetrical(0.w, 16.w),
            ],
          ),
        );
      },
    );
  }

  /// Reusable Input Field
  Widget _buildInputField({
    required String label,
    required String hint,
    required TextEditingController controller,
    required FocusNode focusNode,
    required ValueChanged<String> onChanged,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        label.toText12(
          isBold: true,
          color: AppColors.inputLabelTextColor,
        ),
        TextField(
          controller: controller,
          focusNode: focusNode,
          keyboardType: const TextInputType.numberWithOptions(decimal: true),
          maxLines: 1,
          onChanged: onChanged,
          cursorHeight: 35.h,
          textAlignVertical: TextAlignVertical.center,
          decoration: InputDecoration(
            border: InputBorder.none,
            contentPadding: EdgeInsets.zero,
            isCollapsed: true,
            hintText: hint,
            hintStyle: const TextStyle(color: Colors.grey),
          ),
          style: TextStyle(
            fontSize: 32.f,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
            height: 1.h,
          ),
        ),
      ],
    );
  }
}
