import 'package:easy_localization/easy_localization.dart';
import 'package:fl_chart/fl_chart.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/common_models/data_points.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/date_util.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/presentation/water_monitor/widgets/hydration_tips_widget.dart';
import 'package:hmg_patient_app_new/presentation/water_monitor/widgets/water_intake_summary_widget.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/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/graph/custom_graph.dart';
import 'package:provider/provider.dart';
import 'package:shimmer/shimmer.dart';

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

  @override
  State<WaterConsumptionPage> createState() => _WaterConsumptionPageState();
}

class _WaterConsumptionPageState extends State<WaterConsumptionPage> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await _refreshData();
    });
  }

  /// Refresh data by calling initialize on the view model
  Future<void> _refreshData() async {
    final vm = context.read<WaterMonitorViewModel>();
    await vm.initialize();
  }

  Widget _buildLoadingShimmer({bool isForHistory = true}) {
    return ListView.separated(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      padding: EdgeInsets.all(0.w),
      itemCount: 4,
      separatorBuilder: (_, __) => SizedBox(height: 12.h),
      itemBuilder: (context, index) {
        return Shimmer.fromColors(
          baseColor: AppColors.shimmerBaseColor,
          highlightColor: AppColors.shimmerHighlightColor,
          child: Container(
            height: isForHistory ? 60.h : 40.h,
            decoration: BoxDecoration(
              color: AppColors.whiteColor,
              borderRadius: BorderRadius.circular(10.r),
            ),
          ),
        );
      },
    );
  }

  Widget buildHistoryListTile({required String title, required String subTitle}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            title.toText14(isBold: true, color: AppColors.labelTextColor),
            subTitle.toText18(isBold: true),
          ],
        ),
        Utils.buildSvgWithAssets(icon: AppAssets.greenTickIcon, applyThemeColor: false)
      ],
    ).paddingSymmetrical(0, 8.h);
  }

  Widget _buildHistoryGraphOrList() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 24.w),
      padding: EdgeInsets.all(16.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.r,
        hasShadow: true,
      ),
      child: Consumer(builder: (BuildContext context, WaterMonitorViewModel viewModel, Widget? child) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    LocaleKeys.history.tr(context: context).toText16(isBold: true),
                    SizedBox(width: 8.w),
                    InkWell(
                      onTap: () => _showHistoryDurationBottomsheet(context, viewModel),
                      child: Container(
                        padding: EdgeInsets.symmetric(vertical: 4.h, horizontal: 6.h),
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          backgroundColor: AppColors.greyColor,
                          borderRadius: 8.r,
                          hasShadow: true,
                        ),
                        child: Row(
                          children: [
                            viewModel.selectedDurationFilter.toText12(isBold: true),
                            Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, height: 16.h),
                          ],
                        ),
                      ),
                    )
                  ],
                ),
                InkWell(
                  onTap: () => viewModel.setGraphView(!viewModel.isGraphView),
                  child: AnimatedSwitcher(
                    duration: const Duration(milliseconds: 300),
                    transitionBuilder: (Widget child, Animation<double> animation) {
                      return FadeTransition(
                        opacity: animation,
                        child: ScaleTransition(
                          scale: animation,
                          child: child,
                        ),
                      );
                    },
                    child: Container(
                      key: ValueKey<bool>(viewModel.isGraphView),
                      child: Utils.buildSvgWithAssets(
                        icon: viewModel.isGraphView ? AppAssets.listIcon : AppAssets.graphIcon,
                        height: 24.h,
                        width: 24.h,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            if (!viewModel.isGraphView) _buildHistoryListView(viewModel) else ...[SizedBox(height: 16.h), _buildHistoryGraph()]
          ],
        );
      }),
    );
  }

  Widget _buildHistoryListView(WaterMonitorViewModel viewModel) {
    final selectedDuration = viewModel.selectedDurationFilter;

    // Build list items based on duration
    List<Widget> listItems = [];

    if (selectedDuration == 'Daily') {
      if (viewModel.todayProgressList.isNotEmpty) {
        final todayData = viewModel.todayProgressList.first;
        listItems.add(
          buildHistoryListTile(
            title: "Today's Progress",
            subTitle: "${todayData.quantityConsumed?.toStringAsFixed(0) ?? '0'} ml / ${todayData.quantityLimit?.toStringAsFixed(0) ?? '0'} ml",
          ),
        );
        listItems.add(Divider(height: 1, color: AppColors.dividerColor));
        listItems.add(
          buildHistoryListTile(
            title: "Percentage Completed",
            subTitle: "${todayData.percentageConsumed?.toStringAsFixed(1) ?? '0'}%",
          ),
        );

        // Add history data if available (show ALL entries)
        if (viewModel.historyList.isNotEmpty) {
          listItems.add(Divider(height: 1, color: AppColors.dividerColor));
          listItems.add(
            Padding(
              padding: EdgeInsets.symmetric(vertical: 8.h),
              child: "Water Intake History".toText14(
                weight: FontWeight.w600,
                color: AppColors.textColor,
              ),
            ),
          );

          // Show all history entries
          for (var history in viewModel.historyList) {
            final quantity = "${history.quantity?.toStringAsFixed(0) ?? '0'} ml";
            final time = _formatHistoryDate(history.createdDate ?? '');

            listItems.add(
              buildHistoryListTile(
                title: quantity,
                subTitle: time,
              ),
            );

            if (history != viewModel.historyList.last) {
              listItems.add(Divider(height: 1, color: AppColors.dividerColor));
            }
          }
        }
      } else {
        listItems.add(
          Center(
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 16.h),
              child: "No data available for today".toText14(color: AppColors.greyTextColor),
            ),
          ),
        );
      }
    } else if (selectedDuration == 'Weekly') {
      if (viewModel.weekProgressList.isNotEmpty) {
        // Show previous 6 days + today (total 7 days)
        // API returns data in reverse order (today first), so we reverse it to show oldest to newest (top to bottom)
        // This ensures today appears at the end (bottom)
        final totalDays = viewModel.weekProgressList.length;
        final startIndex = totalDays > 7 ? totalDays - 7 : 0;
        final weekDataToShow = viewModel.weekProgressList.skip(startIndex).toList().reversed.toList();

        for (var dayData in weekDataToShow) {
          listItems.add(
            buildHistoryListTile(
              title: dayData.dayName ?? 'Unknown',
              subTitle: "${dayData.percentageConsumed?.toStringAsFixed(1) ?? '0'}%",
            ),
          );
          if (dayData != weekDataToShow.last) {
            listItems.add(Divider(height: 1, color: AppColors.dividerColor));
          }
        }
      } else {
        listItems.add(
          Center(
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 16.h),
              child: "No data available for this week".toText14(color: AppColors.greyTextColor),
            ),
          ),
        );
      }
    } else if (selectedDuration == 'Monthly') {
      if (viewModel.monthProgressList.isNotEmpty) {
        // Show last 6 months + current month (total 7 months)
        // Show in chronological order: oldest to newest (top to bottom)
        final totalMonths = viewModel.monthProgressList.length;
        final startIndex = totalMonths > 7 ? totalMonths - 7 : 0;
        final monthDataToShow = viewModel.monthProgressList.skip(startIndex).toList();

        for (var monthData in monthDataToShow) {
          listItems.add(
            buildHistoryListTile(
              title: monthData.monthName ?? 'Unknown',
              subTitle: "${monthData.percentageConsumed?.toStringAsFixed(1) ?? '0'}%",
            ),
          );
          if (monthData != monthDataToShow.last) {
            listItems.add(Divider(height: 1, color: AppColors.dividerColor));
          }
        }
      } else {
        listItems.add(
          Center(
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 16.h),
              child: "No data available for this year".toText14(color: AppColors.greyTextColor),
            ),
          ),
        );
      }
    }

    // Return scrollable list with min and max height constraints
    return ConstrainedBox(
      constraints: BoxConstraints(minHeight: 80.h, maxHeight: 270.h),
      child: viewModel.isLoading
          ? _buildLoadingShimmer().paddingOnly(top: 16.h)
          : listItems.isEmpty
              ? Center(
                  child: "No history data available".toText14(color: AppColors.greyTextColor),
                )
              : ListView.separated(
                  padding: EdgeInsets.only(top: 16.h),
                  shrinkWrap: true,
                  itemCount: listItems.length,
                  separatorBuilder: (context, index) => SizedBox.shrink(),
                  itemBuilder: (context, index) => listItems[index],
                ),
    );
  }

  Widget _buildHistoryGraph() {
    return Consumer<WaterMonitorViewModel>(
      builder: (context, viewModel, _) {
        final selectedDuration = viewModel.selectedDurationFilter;

        // Build dynamic data points based on selected duration
        List<DataPoint> dataPoints = [];

        if (selectedDuration == 'Daily') {
          // For daily, show last 7 history entries with at least 5 minutes difference
          if (viewModel.historyList.isNotEmpty) {
            // Filter entries with at least 5 minutes difference
            List<DataPoint> filteredPoints = [];
            DateTime? lastTime;

            for (var historyItem in viewModel.historyList) {
              final currentTime = _parseHistoryDate(historyItem.createdDate ?? '');

              // Add if first entry OR if more than 5 minutes difference from last added entry
              if (lastTime == null || currentTime.difference(lastTime).inMinutes.abs() >= 5) {
                final quantity = historyItem.quantity?.toDouble() ?? 0.0;
                final time = _formatHistoryDate(historyItem.createdDate ?? '');

                filteredPoints.add(
                  DataPoint(
                    value: quantity,
                    actualValue: quantity.toStringAsFixed(0),
                    label: time,
                    displayTime: time,
                    unitOfMeasurement: 'ml',
                    time: currentTime,
                  ),
                );
                lastTime = currentTime;
              }
            }

            // Take only last 7 filtered entries
            final totalFiltered = filteredPoints.length;
            final startIndex = totalFiltered > 7 ? totalFiltered - 7 : 0;
            dataPoints = filteredPoints.skip(startIndex).toList();
          } else if (viewModel.todayProgressList.isNotEmpty) {
            // Fallback: show today's percentage if no history
            final todayData = viewModel.todayProgressList.first;
            final percentage = todayData.percentageConsumed?.toDouble() ?? 0.0;
            dataPoints.add(
              DataPoint(
                value: percentage,
                actualValue: percentage.toStringAsFixed(1),
                label: 'Today',
                displayTime: 'Today',
                unitOfMeasurement: '%',
                time: DateTime.now(),
              ),
            );
          }
        } else if (selectedDuration == 'Weekly') {
          // For weekly, show previous 6 days + today (total 7 days)
          // API returns data in reverse order (today first), so we reverse it to show oldest to newest (left to right)
          // This ensures today appears at the end (right side)
          if (viewModel.weekProgressList.isNotEmpty) {
            final totalDays = viewModel.weekProgressList.length;
            final startIndex = totalDays > 7 ? totalDays - 7 : 0;
            final weekDataToShow = viewModel.weekProgressList.skip(startIndex).toList().reversed.toList();

            for (var dayData in weekDataToShow) {
              final percentage = dayData.percentageConsumed?.toDouble() ?? 0.0;
              final dayName = dayData.dayName ?? 'Day ${dayData.dayNumber}';
              dataPoints.add(
                DataPoint(
                  value: percentage,
                  actualValue: percentage.toStringAsFixed(1),
                  label: DateUtil.getShortWeekDayName(dayName),
                  displayTime: dayName,
                  unitOfMeasurement: '%',
                  time: DateTime.now(),
                ),
              );
            }
          }
        } else if (selectedDuration == 'Monthly') {
          // For monthly, show last 6 months + current month (total 7 months)
          // Show in chronological order: oldest to newest (left to right)
          if (viewModel.monthProgressList.isNotEmpty) {
            final totalMonths = viewModel.monthProgressList.length;
            final startIndex = totalMonths > 7 ? totalMonths - 7 : 0;
            final monthDataToShow = viewModel.monthProgressList.skip(startIndex).toList();

            for (var monthData in monthDataToShow) {
              final percentage = monthData.percentageConsumed?.toDouble() ?? 0.0;
              final monthName = monthData.monthName ?? 'Month ${monthData.monthNumber}';
              dataPoints.add(
                DataPoint(
                  value: percentage,
                  actualValue: percentage.toStringAsFixed(1),
                  label: DateUtil.getShortMonthName(monthName),
                  displayTime: monthName,
                  unitOfMeasurement: '%',
                  time: DateTime.now(),
                ),
              );
            }
          }
        }

        // If no data, show empty state
        if (dataPoints.isEmpty) {
          return Container(
            padding: EdgeInsets.symmetric(vertical: 80.h),
            child: Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Utils.buildSvgWithAssets(
                    icon: AppAssets.graphIcon,
                    iconColor: AppColors.greyTextColor.withValues(alpha: 0.5),
                    height: 32.w,
                    width: 32.w,
                  ),
                  SizedBox(height: 12.h),
                  "No graph data available".toText14(color: AppColors.greyTextColor),
                ],
              ),
            ),
          );
        }

        // Show loading shimmer while fetching data
        if (viewModel.isLoading) {
          return Container(
            padding: EdgeInsets.symmetric(vertical: 40.h),
            child: _buildLoadingShimmer(),
          );
        }

        // Configure graph based on selected duration
        double maxY;
        double minY;
        double horizontalInterval;
        double leftLabelInterval;

        if (selectedDuration == 'Daily') {
          // For daily (quantity in ml), use max available cup size
          // Get the biggest cup from available cups
          final maxCupSize = viewModel.cups.isEmpty ? 500.0 : viewModel.cups.map((cup) => cup.capacityMl.toDouble()).reduce((a, b) => a > b ? a : b);

          maxY = maxCupSize;
          minY = 0;
          // Divide into 4 intervals (5 labels: 0, 1/4, 1/2, 3/4, max)
          horizontalInterval = maxY / 4;
          leftLabelInterval = maxY / 4;
        } else {
          // For weekly/monthly (percentage), use 0-100%
          maxY = 100.0;
          minY = 0;
          horizontalInterval = 25;
          leftLabelInterval = 25;
        }

        return CustomGraph(
          bottomLabelReservedSize: 30,
          dataPoints: dataPoints,
          makeGraphBasedOnActualValue: true,
          leftLabelReservedSize: 50.h,
          showGridLines: true,
          maxY: maxY,
          minY: minY,
          showLinePoints: true,
          maxX: dataPoints.length > 1 ? dataPoints.length.toDouble() - 0.75 : 1.0,
          horizontalInterval: horizontalInterval,
          leftLabelInterval: leftLabelInterval,
          showShadow: true,
          getDrawingHorizontalLine: (value) {
            // Draw dashed lines at intervals
            if (selectedDuration == 'Daily') {
              // For daily, draw lines every 50 or 100 ml
              if (value % horizontalInterval == 0 && value > 0) {
                return FlLine(
                  color: AppColors.greyTextColor.withValues(alpha: 0.3),
                  strokeWidth: 1.5,
                  dashArray: [8, 4],
                );
              }
            } else {
              // For weekly/monthly, draw lines at 25%, 50%, 75%
              if (value == 25 || value == 50 || value == 75) {
                return FlLine(
                  color: AppColors.successColor.withValues(alpha: 0.3),
                  strokeWidth: 1.5,
                  dashArray: [8, 4],
                );
              }
            }
            return FlLine(color: AppColors.transparent, strokeWidth: 0);
          },
          leftLabelFormatter: (value) {
            if (selectedDuration == 'Daily') {
              // Show exactly 5 labels: 0, 1/4, 1/2, 3/4, max
              // Check if value matches one of the 5 positions
              final interval = maxY / 4;
              final positions = [0.0, interval, interval * 2, interval * 3, maxY];

              for (var position in positions) {
                if ((value - position).abs() < 1) {
                  return '${value.toInt()}ml'.toText10(isBold: true);
                }
              }
            } else {
              // Show percentage labels
              if (value == 0) return '0%'.toText10(isBold: true);
              if (value == 25) return '25%'.toText10(isBold: true);
              if (value == 50) return '50%'.toText10(isBold: true);
              if (value == 75) return '75%'.toText10(isBold: true);
              if (value == 100) return '100%'.toText10(isBold: true);
            }
            return SizedBox.shrink();
          },
          graphColor: AppColors.successColor,
          graphShadowColor: AppColors.successColor.withValues(alpha: 0.15),
          bottomLabelFormatter: (value, data) {
            if (data.isEmpty) return SizedBox.shrink();

            // Only show labels for whole number positions (not fractional)
            if ((value - value.round()).abs() > 0.01) {
              return SizedBox.shrink();
            }

            int index = value.round();
            if (index < 0 || index >= data.length) return SizedBox.shrink();

            // For daily, show all 7 time labels (last 7 entries)
            if (selectedDuration == 'Daily' && index < 7) {
              return Padding(
                padding: EdgeInsets.only(top: 10.h),
                child: data[index].label.toText8(
                      isBold: true,
                      color: AppColors.labelTextColor,
                    ),
              );
            }

            // For weekly, show all 7 days (today + last 6 days)
            if (selectedDuration == 'Weekly' && index < 7) {
              return Padding(
                padding: EdgeInsets.only(top: 10.h),
                child: data[index].label.toText10(
                      weight: FontWeight.w600,
                      color: AppColors.labelTextColor,
                    ),
              );
            }

            // For monthly, show all 7 months (current month + last 6 months)
            if (selectedDuration == 'Monthly' && index < 7) {
              return Padding(
                padding: EdgeInsets.only(top: 10.h),
                child: data[index].label.toText10(isBold: true, color: AppColors.labelTextColor),
              );
            }

            return SizedBox.shrink();
          },
          scrollDirection: selectedDuration == 'Monthly' ? Axis.horizontal : Axis.vertical,
          height: 250.h,
          spotColor: AppColors.successColor,
        );
      },
    );
  }

  // 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),
    );
  }

  void _showSelectionBottomSheet({
    required BuildContext context,
    required String title,
    required List<String> items,
    required String selectedValue,
    required Function(String) onSelected,
    bool useUpperCase = false,
  }) {
    final dialogService = getIt.get<DialogService>();

    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 _showHistoryDurationBottomsheet(BuildContext context, WaterMonitorViewModel viewModel) {
    _showSelectionBottomSheet(
      context: context,
      title: LocaleKeys.selectDuration.tr(context: context),
      items: viewModel.durationFilters,
      selectedValue: viewModel.selectedDurationFilter,
      onSelected: viewModel.setFilterDuration,
    );
  }

  /// Handle reminder button tap (Set or Cancel)
  Future<void> _handleReminderButtonTap(WaterMonitorViewModel viewModel) async {
    if (viewModel.isWaterReminderEnabled) {
      // Cancel reminders
      _showCancelReminderConfirmation(viewModel);
    } else {
      // Set reminders
      await _setReminders(viewModel);
    }
  }

  /// Show confirmation bottom sheet before cancelling reminders
  void _showCancelReminderConfirmation(WaterMonitorViewModel viewModel) {
    showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.notice.tr(context: context),
      context,
      child: Utils.getWarningWidget(
        loadingText: LocaleKeys.areYouSureYouWantToCancelAllWaterReminders.tr(context: context),
        isShowActionButtons: true,
        onCancelTap: () {
          Navigator.pop(context);
        },
        onConfirmTap: () async {
          Navigator.pop(context);
          await _cancelReminders(viewModel);
        },
      ),
      callBackFunc: () {},
      isFullScreen: false,
      isCloseButtonVisible: true,
      isDismissible: true,
    );
  }

  /// Set water reminders
  Future<void> _setReminders(WaterMonitorViewModel viewModel) async {
    // Schedule reminders
    final success = await viewModel.scheduleWaterReminders();

    if (success) {
      final times = await viewModel.getScheduledReminderTimes();
      _showReminderScheduledDialog(times);
    }
  }

  /// Cancel water reminders
  Future<void> _cancelReminders(WaterMonitorViewModel viewModel) async {
    final success = await viewModel.cancelWaterReminders();
  }

  /// Show bottom sheet with scheduled reminder times
  void _showReminderScheduledDialog(List<DateTime> times) {
    showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.remindersSet.tr(context: context),
      context,
      isCloseButtonVisible: false,
      isDismissible: false,
      child: Padding(
        padding: EdgeInsets.only(top: 16.w, left: 16.w, right: 16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Utils.getSuccessWidget(loadingText: LocaleKeys.dailyWaterRemindersScheduledAt.tr(context: context)),
            SizedBox(height: 16.h),
            Wrap(
              spacing: 8.w,
              runSpacing: 8.h,
              children: times
                  .map(
                    (time) => AppCustomChipWidget(
                      icon: AppAssets.bell,
                      iconColor: AppColors.quickLoginColor,
                      richText: _formatTime(time).toText14(),
                      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 8.h),
                    ),
                  )
                  .toList(),
            ),

            SizedBox(height: 24.h),

            // OK button
            Row(
              children: [
                Expanded(
                  child: CustomButton(
                    height: 56.h,
                    text: LocaleKeys.ok.tr(context: context),
                    onPressed: () => Navigator.of(context).pop(),
                    textColor: AppColors.whiteColor,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
      callBackFunc: () {},
    );
  }

  /// Format DateTime to readable time string
  String _formatTime(DateTime time) {
    final hour = time.hour;
    final minute = time.minute;
    final hour12 = hour > 12 ? hour - 12 : (hour == 0 ? 12 : hour);
    final period = hour >= 12 ? 'PM' : 'AM';
    return '${hour12.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')} $period';
  }

  /// Format history date from /Date(milliseconds+0300)/ format
  String _formatHistoryDate(String dateString) {
    try {
      // Parse the /Date(milliseconds+0300)/ format
      final regex = RegExp(r'\/Date\((\d+)');
      final match = regex.firstMatch(dateString);
      if (match != null) {
        final milliseconds = int.tryParse(match.group(1)!);
        if (milliseconds != null) {
          final dateTime = DateTime.fromMillisecondsSinceEpoch(milliseconds);
          return _formatTime(dateTime);
        }
      }
    } catch (e) {
      return dateString;
    }
    return dateString;
  }

  /// Parse history date from /Date(milliseconds+0300)/ format to DateTime
  DateTime _parseHistoryDate(String dateString) {
    try {
      final regex = RegExp(r'\/Date\((\d+)');
      final match = regex.firstMatch(dateString);
      if (match != null) {
        final milliseconds = int.tryParse(match.group(1)!);
        if (milliseconds != null) {
          return DateTime.fromMillisecondsSinceEpoch(milliseconds);
        }
      }
    } catch (e) {
      // Return current time as fallback
    }
    return DateTime.now();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        title: LocaleKeys.waterConsumption.tr(context: context),
        bottomChild: Consumer<WaterMonitorViewModel>(
          builder: (context, viewModel, child) {
            return Container(
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 24.r,
                hasShadow: true,
              ),
              child: Padding(
                padding: EdgeInsets.all(24.w),
                child: CustomButton(
                  text: viewModel.isWaterReminderEnabled ? LocaleKeys.cancelReminder.tr(context: context) : LocaleKeys.setReminder.tr(context: context),
                  textColor: viewModel.isWaterReminderEnabled ? AppColors.errorColor : AppColors.successColor,
                  backgroundColor: viewModel.isWaterReminderEnabled ? AppColors.errorColor.withValues(alpha: 0.1) : AppColors.successLightBgColor,
                  onPressed: () => _handleReminderButtonTap(viewModel),
                  icon: viewModel.isWaterReminderEnabled ? null : AppAssets.bell,
                  iconColor: viewModel.isWaterReminderEnabled ? AppColors.errorColor : AppColors.successColor,
                  borderRadius: 12.r,
                  borderColor: AppColors.transparent,
                  padding: EdgeInsets.symmetric(vertical: 14.h),
                ),
              ),
            );
          },
        ),
        child: RefreshIndicator(
          onRefresh: _refreshData,
          color: AppColors.blueColor,
          backgroundColor: AppColors.whiteColor,
          child: Column(
            children: [
              SizedBox(height: 16.h),
              const WaterIntakeSummaryWidget(),
              SizedBox(height: 16.h),
              _buildHistoryGraphOrList(),
              SizedBox(height: 16.h),
              const HydrationTipsWidget(),
              SizedBox(height: 16.h),
            ],
          ),
        ),
      ),
    );
  }
}
