import 'dart:developer';

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/dependencies.dart';
import 'package:hmg_patient_app_new/core/enums.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/features/health_trackers/health_trackers_view_model.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:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

class AddHealthTrackerEntryPage extends StatefulWidget {
  final HealthTrackerTypeEnum trackerType;

  const AddHealthTrackerEntryPage({
    super.key,
    required this.trackerType,
  });

  @override
  State<AddHealthTrackerEntryPage> createState() => _AddHealthTrackerEntryPageState();
}

class _AddHealthTrackerEntryPageState extends State<AddHealthTrackerEntryPage> {
  late DialogService dialogService;

  // Controllers for date and time
  final TextEditingController dateController = TextEditingController();
  final TextEditingController timeController = TextEditingController();

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

    // Clear errors when entering the page
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final viewModel = context.read<HealthTrackersViewModel>();
      viewModel.clearAllFieldErrors();
    });
  }

  @override
  void dispose() {
    dateController.dispose();
    timeController.dispose();

    // Clear errors when leaving the page
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        final viewModel = context.read<HealthTrackersViewModel>();
        viewModel.clearAllFieldErrors();
      }
    });

    super.dispose();
  }

  /// Get page title based on tracker type
  String _getPageTitle() {
    switch (widget.trackerType) {
      case HealthTrackerTypeEnum.bloodSugar:
        return LocaleKeys.addBloodSugar.tr(context: context);
      case HealthTrackerTypeEnum.bloodPressure:
        return LocaleKeys.addBloodPressure.tr(context: context);
      case HealthTrackerTypeEnum.weightTracker:
        return LocaleKeys.addWeight.tr(context: context);
    }
  }

  /// Get success message based on tracker type
  String _getSuccessMessage() {
    switch (widget.trackerType) {
      case HealthTrackerTypeEnum.bloodSugar:
        return LocaleKeys.bloodSugarDataSavedSuccessfully.tr(context: context);
      case HealthTrackerTypeEnum.bloodPressure:
        return LocaleKeys.bloodPressureDataSavedSuccessfully.tr(context: context);
      case HealthTrackerTypeEnum.weightTracker:
        return LocaleKeys.weightDataSavedSuccessfully.tr(context: context);
    }
  }

  /// Save entry based on tracker type
  Future<void> _saveEntry(HealthTrackersViewModel viewModel) async {
    switch (widget.trackerType) {
      case HealthTrackerTypeEnum.bloodSugar:
        await _saveBloodSugarEntry(viewModel);
        break;
      case HealthTrackerTypeEnum.bloodPressure:
        await _saveBloodPressureEntry(viewModel);
        break;
      case HealthTrackerTypeEnum.weightTracker:
        await _saveWeightEntry(viewModel);
        break;
    }
  }

  // Save Blood Sugar entry
  Future<void> _saveBloodSugarEntry(HealthTrackersViewModel viewModel) async {
    // Combine date and time
    final dateTime = "${dateController.text} ${timeController.text}";

    // Validate using ViewModel method that sets field errors
    if (!viewModel.validateBloodSugarEntry(dateTime)) {
      // Validation failed, errors are already set in viewModel
      return;
    }

    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.pleaseWait.tr(context: context));

    // Call ViewModel method with callbacks
    await viewModel.saveBloodSugarEntry(
      dateTime: dateTime,
      measureTime: viewModel.selectedBloodSugarMeasureTime,
      onSuccess: () {
        LoaderBottomSheet.hideLoader();
        _showSuccessAndPop();
      },
      onFailure: (error) {
        LoaderBottomSheet.hideLoader();
        dialogService.showErrorBottomSheet(message: error);
      },
    );
  }

  // Save Weight entry
  Future<void> _saveWeightEntry(HealthTrackersViewModel viewModel) async {
    // Combine date and time
    final dateTime = "${dateController.text} ${timeController.text}";

    // Validate using ViewModel method that sets field errors
    if (!viewModel.validateWeightEntry(dateTime)) {
      // Validation failed, errors are already set in viewModel
      return;
    }

    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.pleaseWait.tr(context: context));

    // Call ViewModel method with callbacks
    await viewModel.saveWeightEntry(
      dateTime: dateTime,
      onSuccess: () {
        LoaderBottomSheet.hideLoader();
        _showSuccessAndPop();
      },
      onFailure: (error) {
        LoaderBottomSheet.hideLoader();
        dialogService.showErrorBottomSheet(message: error);
      },
    );
  }

  // Save Blood Pressure entry
  Future<void> _saveBloodPressureEntry(HealthTrackersViewModel viewModel) async {
    // Combine date and time
    final dateTime = "${dateController.text} ${timeController.text}";

    // Validate using ViewModel method that sets field errors
    if (!viewModel.validateBloodPressureEntry(dateTime)) {
      // Validation failed, errors are already set in viewModel
      return;
    }

    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.pleaseWait.tr(context: context));

    // Call ViewModel method with callbacks
    await viewModel.saveBloodPressureEntry(
      dateTime: dateTime,
      onSuccess: () {
        LoaderBottomSheet.hideLoader();
        _showSuccessAndPop();
      },
      onFailure: (error) {
        LoaderBottomSheet.hideLoader();
        dialogService.showErrorBottomSheet(message: error);
      },
    );
  }

  // Show success message and pop back

  void _showSuccessAndPop() async {
    showCommonBottomSheetWithoutHeight(context,
        child: Utils.getSuccessWidget(
          loadingText: _getSuccessMessage(),
        ).paddingSymmetrical(0.h, 24.h), callBackFunc: () {
      // Navigator.pop(context);
    }, isCloseButtonVisible: false, isDismissible: true, isFullScreen: false, isAutoDismiss: false);
    await Future.delayed(Duration(milliseconds: 2000)).then((value) {
      if (mounted) {
        Navigator.pop(context);
        Navigator.pop(context);
      }
    });
  }

  // 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(
        constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.7),
        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: () {},
    );
  }

  // Blood Sugar unit selection
  void _showBloodSugarUnitSelectionBottomSheet(BuildContext context, HealthTrackersViewModel viewModel) {
    FocusScope.of(context).unfocus();
    _showSelectionBottomSheet(
      context: context,
      title: LocaleKeys.selectUnit.tr(context: context),
      items: viewModel.bloodSugarUnit,
      selectedValue: viewModel.selectedBloodSugarUnit,
      onSelected: viewModel.setBloodSugarUnit,
      useUpperCase: false,
    );
  }

  // Blood Sugar measure time selection
  void _showBloodSugarEntryTimeBottomSheet(BuildContext context, HealthTrackersViewModel viewModel) {
    FocusScope.of(context).unfocus();
    _showSelectionBottomSheet(
      context: context,
      title: LocaleKeys.selectMeasureTime.tr(context: context),
      items: viewModel.getBloodSugarTimeList(),
      selectedValue: viewModel.selectedBloodSugarMeasureTime,
      onSelected: viewModel.setBloodSugarMeasureTime,
      useUpperCase: false,
    );
  }

  // Weight unit selection
  void _showWeightUnitSelectionBottomSheet(BuildContext context, HealthTrackersViewModel viewModel) {
    FocusScope.of(context).unfocus();
    _showSelectionBottomSheet(
      context: context,
      title: LocaleKeys.selectUnit.tr(context: context),
      items: viewModel.getWeightUnitsList(),
      selectedValue: viewModel.selectedWeightUnitDisplay,
      onSelected: viewModel.setWeightUnit,
      useUpperCase: false,
    );
  }

  // Blood Pressure measured arm selection
  void _showMeasuredArmSelectionBottomSheet(BuildContext context, HealthTrackersViewModel viewModel) {
    FocusScope.of(context).unfocus();
    _showSelectionBottomSheet(
      context: context,
      title: LocaleKeys.selectArm.tr(context: context),
      items: viewModel.getMeasuredArmList(),
      selectedValue: viewModel.selectedMeasuredArmDisplay,
      onSelected: viewModel.setMeasuredArm,
      useUpperCase: false,
    );
  }

  // Reusable method to build text field
  Widget _buildTextField(
    TextEditingController controller,
    String hintText, {
    TextInputType keyboardType = TextInputType.name,
    Function(String)? onChanged,
  }) {
    return TextField(
      controller: controller,
      keyboardType: keyboardType,
      maxLines: 1,
      cursorHeight: 14.h,
      textAlignVertical: TextAlignVertical.center,
      onChanged: onChanged,
      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,
      ),
    );
  }

  // Build error text widget
  Widget _buildErrorText(String errorMessage) {
    return Padding(
      padding: EdgeInsets.only(left: 52.w, top: 4.h, bottom: 4.h),
      child: Align(
        alignment: Alignment.centerLeft,
        child: Text(
          errorMessage,
          style: TextStyle(
            color: AppColors.primaryRedColor,
            fontSize: 12.f,
          ),
        ),
      ),
    );
  }

  // Reusable method to build settings row
  Widget _buildSettingsRow({
    required String icon,
    required String label,
    String? value,
    Widget? inputField,
    String? unit,
    VoidCallback? onUnitTap,
    VoidCallback? onRowTap,
    Color? iconColor,
    bool showDivider = true,
  }) {
    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, iconColor: iconColor)),
            ),
            SizedBox(width: 12.w),
            Expanded(
              flex: unit != null ? 2 : 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.isNotEmpty)
                    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: [
                        LocaleKeys.unit.tr(context: context).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: 8.w),
            ],
          ],
        ).paddingSymmetrical(0.w, 16.w).onPress(onRowTap ?? () {}),
        if (showDivider) Divider(height: 1, color: AppColors.dividerColor),
      ],
    );
  }

  /// Build form fields based on tracker type
  Widget _buildFormFields(HealthTrackersViewModel viewModel) {
    switch (widget.trackerType) {
      case HealthTrackerTypeEnum.bloodSugar:
        return _buildBloodSugarForm(viewModel);
      case HealthTrackerTypeEnum.bloodPressure:
        return _buildBloodPressureForm(viewModel);
      case HealthTrackerTypeEnum.weightTracker:
        return _buildWeightForm(viewModel);
    }
  }

  /// Blood Sugar form fields
  Widget _buildBloodSugarForm(HealthTrackersViewModel viewModel) {
    return Selector<HealthTrackersViewModel, bool>(
      selector: (_, model) => model.hasBloodSugarFormError,
      builder: (context, hasError, child) {
        return 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,
            side: hasError
                ? BorderSide(color: AppColors.primaryRedBorderColor, width: 1)
                : null,
          ),
          child: Column(
            children: [
              _buildSettingsRow(
                icon: AppAssets.heightIcon,
                label: LocaleKeys.enterBloodSugar.tr(context: context),
                inputField: _buildTextField(
                  viewModel.bloodSugarController,
                  '',
                  keyboardType: TextInputType.number,
                  onChanged: (value) => viewModel.clearBloodSugarError(),
                ),
                unit: viewModel.selectedBloodSugarUnit,
                onUnitTap: () => _showBloodSugarUnitSelectionBottomSheet(context, viewModel),
              ),
              if (viewModel.bloodSugarError != null)
                _buildErrorText(viewModel.bloodSugarError!),
              _buildDateTimeFields(),
              Divider(height: 1, color: AppColors.dividerColor),
              _buildSettingsRow(
                icon: AppAssets.weight_tracker_icon,
                label: LocaleKeys.selectMeasureTime.tr(context: context),
                value: viewModel.selectedBloodSugarMeasureTime,
                onRowTap: () => _showBloodSugarEntryTimeBottomSheet(context, viewModel),
              ),
              if (viewModel.bloodSugarMeasureTimeError != null)
                _buildErrorText(viewModel.bloodSugarMeasureTimeError!),
            ],
          ),
        );
      },
    );
  }

  /// Blood Pressure form fields
  Widget _buildBloodPressureForm(HealthTrackersViewModel viewModel) {
    return Selector<HealthTrackersViewModel, bool>(
      selector: (_, model) => model.hasBloodPressureFormError,
      builder: (context, hasError, child) {
        return 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,
            side: hasError
                ? BorderSide(color: AppColors.primaryRedBorderColor, width: 1)
                : null,
          ),
          child: Column(
            children: [
              _buildSettingsRow(
                icon: AppAssets.bloodPressureIcon,
                iconColor: AppColors.greyTextColor,
                label: LocaleKeys.enterSystolicValue.tr(context: context),
                inputField: _buildTextField(
                  viewModel.systolicController,
                  '',
                  keyboardType: TextInputType.number,
                  onChanged: (value) => viewModel.clearSystolicError(),
                ),
              ),
              if (viewModel.systolicError != null)
                _buildErrorText(viewModel.systolicError!),
              _buildSettingsRow(
                icon: AppAssets.bloodPressureIcon,
                iconColor: AppColors.greyTextColor,
                label: LocaleKeys.enterDiastolicValue.tr(context: context),
                inputField: _buildTextField(
                  viewModel.diastolicController,
                  '',
                  keyboardType: TextInputType.number,
                  onChanged: (value) => viewModel.clearDiastolicError(),
                ),
              ),
              if (viewModel.diastolicError != null)
                _buildErrorText(viewModel.diastolicError!),
              _buildSettingsRow(
                icon: AppAssets.bodyIcon,
                iconColor: AppColors.greyTextColor,
                label: LocaleKeys.selectArm.tr(context: context),
                value: viewModel.selectedMeasuredArmDisplay,
                onRowTap: () {
                  _showMeasuredArmSelectionBottomSheet(context, viewModel);
                  viewModel.clearMeasuredArmError();
                },
              ),
              if (viewModel.measuredArmError != null)
                _buildErrorText(viewModel.measuredArmError!),
              _buildDateTimeFields(),
            ],
          ),
        );
      },
    );
  }

  /// Weight form fields
  Widget _buildWeightForm(HealthTrackersViewModel viewModel) {
    return Selector<HealthTrackersViewModel, bool>(
      selector: (_, model) => model.hasWeightFormError,
      builder: (context, hasError, child) {
        return 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,
            side: hasError
                ? BorderSide(color: AppColors.primaryRedBorderColor, width: 1)
                : null,
          ),
          child: Column(
            children: [
              _buildSettingsRow(
                icon: AppAssets.weightScale,
                label: LocaleKeys.enterWeight.tr(context: context),
                inputField: _buildTextField(
                  viewModel.weightController,
                  '',
                  keyboardType: TextInputType.number,
                  onChanged: (value) => viewModel.clearWeightError(),
                ),
                unit: viewModel.selectedWeightUnitDisplay,
                onUnitTap: () => _showWeightUnitSelectionBottomSheet(context, viewModel),
              ),
              if (viewModel.weightError != null)
                _buildErrorText(viewModel.weightError!),
              _buildDateTimeFields(),
            ],
          ),
        );
      },
    );
  }

  /// Common date and time fields
  Widget _buildDateTimeFields() {
    return Consumer<HealthTrackersViewModel>(
      builder: (context, viewModel, child) {
        return Column(
          children: [
            SizedBox(width: 8.w),
            TextInputWidget(
              controller: dateController,
              isReadOnly: true,
              isArrowTrailing: true,
              labelText: LocaleKeys.date.tr(context: context),
              hintText: LocaleKeys.pickADate.tr(context: context),
              focusNode: FocusNode(),
              isEnable: true,
              prefix: null,
              isAllowRadius: true,
              isBorderAllowed: false,
              isAllowLeadingIcon: true,
              padding: EdgeInsets.symmetric(vertical: 8.h),
              leadingIcon: AppAssets.calendarGrey,
              selectionType: SelectionTypeEnum.calendar,
              isHideSwitcher: true,
              btnTitle: LocaleKeys.add.tr(context: context),
              onCalendarTypeChanged: (val) {},
              onChange: (val) {
                if (val == null) return;
                try {
                  final parsedDate = DateTime.parse(val);
                  final formattedDate = DateFormat('dd MMM yyyy').format(parsedDate);
                  dateController.text = formattedDate;
                  viewModel.clearDateError();
                  log("date: $formattedDate");
                } catch (e) {
                  dateController.text = val;
                  viewModel.clearDateError();
                  log("date: $val");
                }
              },
            ),
            if (viewModel.dateError != null)
              _buildErrorText(viewModel.dateError!),
            Divider(height: 1, color: AppColors.dividerColor),
            SizedBox(width: 8.w),
            TextInputWidget(
              controller: timeController,
              isReadOnly: true,
              isArrowTrailing: true,
              labelText: LocaleKeys.time.tr(context: context),
              hintText: LocaleKeys.selectMeasureTime.tr(context: context),
              focusNode: FocusNode(),
              isEnable: true,
              prefix: null,
              isAllowRadius: true,
              isBorderAllowed: false,
              isAllowLeadingIcon: true,
              padding: EdgeInsets.symmetric(vertical: 8.h),
              leadingIcon: AppAssets.calendarGrey,
              selectionType: SelectionTypeEnum.time,
              isHideSwitcher: true,
              onCalendarTypeChanged: (val) {},
              onChange: (val) {
                if (val == null) return;
                timeController.text = val;
                viewModel.clearTimeError();
                log("time: $val");
              },
            ),
            if (viewModel.timeError != null)
              _buildErrorText(viewModel.timeError!),
          ],
        );
      },
    );
  }

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

    return GestureDetector(
      onTap: () {
        FocusScope.of(context).unfocus();
      },
      child: Scaffold(
        backgroundColor: AppColors.bgScaffoldColor,
        body: CollapsingListView(
          title: _getPageTitle(),
          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 => await _saveEntry(viewModel),
                borderRadius: 12.r,
                padding: EdgeInsets.symmetric(vertical: 14.h),
              ),
            ),
          ),
          child: _buildFormFields(viewModel),
        ),
      ),
    );
  }
}
