import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.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/generated/locale_keys.g.dart';
import 'package:provider/provider.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/enums.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/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/health_calculator_view_model.dart';

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

  OvulationWidget({super.key, required this.onChange});

  @override
  _OvulationWidgetState createState() => _OvulationWidgetState();
}

class _OvulationWidgetState extends State<OvulationWidget> {
  final TextEditingController _ageController = TextEditingController();
  final TextEditingController _cycleLengthController = TextEditingController();
  final TextEditingController _lutealPhaseLengthController = TextEditingController();
  Function(String)? onUnitSelected;
  String selectedDate = '';

  @override
  void initState() {
    super.initState();
    _ageController.addListener(_onInputChanged);
    _cycleLengthController.addListener(_onInputChanged);
    _lutealPhaseLengthController.addListener(_onInputChanged);
  }

  @override
  void dispose() {
    _ageController.removeListener(_onInputChanged);
    _cycleLengthController.removeListener(_onInputChanged);
    _lutealPhaseLengthController.removeListener(_onInputChanged);
    _ageController.dispose();
    _cycleLengthController.dispose();
    _lutealPhaseLengthController.dispose();
    super.dispose();
  }

  void _onInputChanged() {
    final provider = Provider.of<HealthCalcualtorViewModel>(context, listen: false);
    final dateText = selectedDate.isEmpty ? _ageController.text.trim() : selectedDate;
    provider.calculateOvulation(dateText: dateText, cycleLengthText: _cycleLengthController.text, lutealPhaseText: _lutealPhaseLengthController.text);
    if (widget.onChange != null) widget.onChange!(provider.ovulationResult);
  }

  @override
  Widget build(BuildContext context) {
    AppState appState = getIt<AppState>();
    return Consumer<HealthCalcualtorViewModel>(builder: (context, provider, _) {
      return Container(
        margin: EdgeInsets.zero,
        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: [
            TextInputWidget(
              labelText: "Date",
              hintText: "11 July, 1994",
              controller: _ageController,
              isEnable: true,
              prefix: null,
              isAllowRadius: true,
              isBorderAllowed: false,
              isAllowLeadingIcon: true,
              padding: EdgeInsets.symmetric(vertical: 8.h),
              leadingIcon: AppAssets.birthday_cake,
              selectionType: SelectionTypeEnum.calendar,
              isHideSwitcher: true,
              onCalendarTypeChanged: (val) {},
              onChange: (val) {
                if (val == null) return;
                setState(() {
                  _ageController.text = selectedDate = Utils.formatDateToDisplay(val);
                });
                _onInputChanged();
              },
            ).withVerticalPadding(8),
            Divider(height: 1, color: Color(0xFFEEEEEE)),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Utils.buildSvgWithAssets(icon: AppAssets.age, width: 40.w, height: 40.w, applyThemeColor: false),
                SizedBox(width: 12.w),
                Expanded(
                  flex: 3,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      LocaleKeys.averageCycleLength.tr(context: context).toText12(isBold: true, color: AppColors.inputLabelTextColor),
                      Container(
                        height: 20.w,
                        alignment: Alignment.centerLeft,
                        child: TextField(
                          controller: _cycleLengthController,
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          cursorHeight: 14,
                          textAlignVertical: TextAlignVertical.center,
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.zero,
                            isCollapsed: true,
                            hintText: '28',
                            hintStyle: TextStyle(color: Colors.grey),
                          ),
                          style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: Colors.black87, height: 1.0),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
            Divider(height: 1, color: Color(0xFFEEEEEE)),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Utils.buildSvgWithAssets(icon: AppAssets.age, width: 40.w, height: 40.w, applyThemeColor: false),
                SizedBox(width: 12.w),
                Expanded(
                  flex: 3,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      LocaleKeys.averageLutealPhase.tr(context: context).toText12(isBold: true, color: AppColors.inputLabelTextColor),
                      Container(
                        height: 20.w,
                        alignment: Alignment.centerLeft,
                        child: TextField(
                          controller: _lutealPhaseLengthController,
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          cursorHeight: 14,
                          textAlignVertical: TextAlignVertical.center,
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.zero,
                            isCollapsed: true,
                            hintText: '14',
                            hintStyle: TextStyle(color: Colors.grey),
                          ),
                          style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: Colors.black87, height: 1.0),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Utils.buildSvgWithAssets(icon: AppAssets.globe, width: 18.w, height: 18.w),
                SizedBox(width: 12.w),
                Expanded(
                  child: appState.isArabic()
                      ? "احسب فترة الإباضة وفترة الخصوبة بناءً على آخر دورة شهرية وطول الدورة الشهرية ومرحلة الجسم الأصفر.".toText12(isBold: true, color: AppColors.inputLabelTextColor)
                      : "Calculate ovulation and fertile window based on last period, cycle length and luteal phase.".toText12(isBold: true, color: AppColors.inputLabelTextColor),
                ),
              ],
            ).paddingSymmetrical(0.w, 16.w),
          ],
        ),
      );
    });
  }
}
