
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/core/utils/calender_utils_new.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:flutter/cupertino.dart';
import '../../core/app_assets.dart';
import '../../features/active_prescriptions/active_prescriptions_view_model.dart';
import '../../features/active_prescriptions/models/active_prescriptions_response_model.dart';
import '../../generated/locale_keys.g.dart';
import '../../theme/colors.dart';
import '../../widgets/appbar/app_bar_widget.dart';
import 'package:intl/intl.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import '../../widgets/buttons/custom_button.dart';
import '../../widgets/chip/app_custom_chip_widget.dart'; // for date formatting
import 'package:provider/provider.dart';
import '../../widgets/loader/bottomsheet_loader.dart';
import 'package:shared_preferences/shared_preferences.dart';


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

  @override
  State<ActiveMedicationPage> createState() => _ActiveMedicationPageState();
}

class _ActiveMedicationPageState extends State<ActiveMedicationPage> {
  late DateTime currentDate;
  late DateTime selectedDate;
  List<ActivePrescriptionsResponseModel> selectedDayMeds = [];
  ActivePrescriptionsViewModel? activePreVM;

  Map<String, bool> medReminderStatus = {};

  String _buildMedKey(ActivePrescriptionsResponseModel med) {
    return "${med.itemId}_${med.startDate}_${med.days}_${med.frequency}";
  }

  int _getDosesCount(ActivePrescriptionsResponseModel med) {
    return  med.frequencyNumber ?? 1;
  }

  @override
  void initState() {
    super.initState();
    currentDate = DateTime.now();
    selectedDate = currentDate;

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      activePreVM =
          Provider.of<ActivePrescriptionsViewModel>(context, listen: false);
      LoaderBottomSheet.showLoader();
      await activePreVM!.getActiveMedications(
        onSuccess: (_) async {
          LoaderBottomSheet.hideLoader();

          final todayMeds =
          activePreVM!.getMedsForSelectedDay(selectedDate);
          setState(() => selectedDayMeds = todayMeds);

          WidgetsBinding.instance.addPostFrameCallback((_) async {
            await loadSavedReminders();
          });
        },
        onError: (_) {
          LoaderBottomSheet.hideLoader();
        },
      );

      activePreVM!.addListener(() {
        if (!mounted) return;
        final medsForDay =
        activePreVM!.getMedsForSelectedDay(selectedDate);
        setState(() => selectedDayMeds = medsForDay);
      });
    });
  }

  Future<void> loadSavedReminders() async {
    final prefs = await SharedPreferences.getInstance();

    for (final med in activePreVM!.activePrescriptionsDetailsList) {
      final medKey = _buildMedKey(med);
      final doses = _getDosesCount(med);

      med.selectedDoseTimes =
      List<String?>.filled(doses, null, growable: false);

      for (int i = 0; i < doses; i++) {
        final saved = prefs.getString("doseTime_${medKey}_$i");
        if (saved != null) {
          med.selectedDoseTimes[i] = saved;
        }
      }

      final reminderOn =
          prefs.getBool("reminderStatus_$medKey") ?? false;
      med.isReminderOn = reminderOn;
      medReminderStatus[medKey] = reminderOn;
    }

    setState(() {});
  }

  Future<void> saveReminderStatus(String medKey, bool value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool("reminderStatus_$medKey", value);
  }

  Future<void> saveDoseTime(
      String medKey, int doseIndex, String time) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString("doseTime_${medKey}_$doseIndex", time);
  }

  List<DateTime> getUpcomingDays() =>
      List.generate(7, (index) => currentDate.add(Duration(days: index)));

  @override
  Widget build(BuildContext context) {
    final days = getUpcomingDays();
    return Scaffold(
      backgroundColor: AppColors.scaffoldBgColor,
      appBar: CustomAppBar(
        onBackPressed: () => Navigator.of(context).pop(),
        onLanguageChanged: (_) {},
        hideLogoAndLang: true,
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(LocaleKeys.activeMedications.tr(),
              style: TextStyle(
                  color: AppColors.textColor,
                  fontSize: 27.f,
                fontWeight: FontWeight.w600,)),
          SizedBox(height: 16.h),
          SizedBox(
            height: 65.h,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: days.length,
              itemBuilder: (context, index) {
                final day = days[index];
                final label = DateFormat('E').format(day);
                return Padding(
                  padding: const EdgeInsets.only(right: 12),
                  child: buildDayCard(label, day),
                );
              },
            ),
          ),
          SizedBox(height: 20.h),
          RichText(
            text: TextSpan(
              children: [
                TextSpan(
                  text: "${selectedDate.day}",
                  style: TextStyle(
                    color: AppColors.textColor,
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                WidgetSpan(
                  child: Transform.translate(
                    offset: const Offset(0, -4),
                    child: Text(
                      _getSuffix(selectedDate.day),
                      style: TextStyle(
                        fontSize: 12,
                        color: AppColors.textColor,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
                TextSpan(
                  text: "  ${DateFormat.MMMM().format(selectedDate)}",
                  style: TextStyle(
                    color: AppColors.textColor,
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),
          Text(LocaleKeys.medications.tr(),
              style: TextStyle(
                  color: AppColors.primaryRedBorderColor,
                  fontSize: 12.f,
                fontWeight: FontWeight.w600,)),
          SizedBox(height: 16.h),
          Expanded(
            child: SingleChildScrollView(
              child: selectedDayMeds.isNotEmpty
                  ? ListView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: selectedDayMeds.length,
                itemBuilder: (context, index) {
                  final med = selectedDayMeds[index];
                  final doses = _getDosesCount(med);
                  if (med.selectedDoseTimes.length != doses) {
                    final old = med.selectedDoseTimes;
                    med.selectedDoseTimes =
                    List<String?>.filled(doses, null,
                        growable: false);
                    for (int i = 0;
                    i < old.length && i < doses;
                    i++) {
                      med.selectedDoseTimes[i] = old[i];
                    }
                  }

                  return Container(
                    decoration: RoundedRectangleBorder()
                        .toSmoothCornerDecoration(
                      color: AppColors.whiteColor,
                      borderRadius: 24.r,
                      hasShadow: true,
                    ),
                    margin: EdgeInsets.all(10),
                    child: Column(
                      children: [
                        _buildMedHeader(med),
                        Row(
                          crossAxisAlignment:
                          CrossAxisAlignment.center,
                          children: [
                            // Utils.buildSvgWithAssets(
                            //   icon: AppAssets.,
                            //   height: 18.h,
                            //   width: 18.h,
                            //   iconColor:
                            //   AppColors.lightGreyTextColor,
                            // ),
                            Icon(
                              Icons.info_outline,
                              color: AppColors
                                  .lightGreyTextColor,
                              size: 18,
                            ),
                            SizedBox(width: 6.h),
                            Expanded(
                              child: RichText(
                                text: TextSpan(
                                  children: [
                                    TextSpan(
                                      text: LocaleKeys.remarks.tr(),
                                      style: TextStyle(
                                        color:
                                        AppColors.textColor,
                                        fontWeight:
                                        FontWeight.w600,
                                        fontSize: 10,
                                      ),
                                    ),
                                    TextSpan(
                                      text:
                                      LocaleKeys.someRemarksAboutPrescription.tr(),
                                      style: TextStyle(
                                        color: AppColors
                                            .lightGreyTextColor,
                                        fontWeight:
                                        FontWeight.normal,
                                        fontSize: 10,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ).paddingOnly(left: 16, right: 16),
                        Divider(
                            color: AppColors.greyColor),
                        GestureDetector(
                          onTap: () => showDoseDialog(med),
                          child: Row(
                            children: [
                              Container(
                                width: 40.h,
                                height: 40.h,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  color: AppColors.greyColor,
                                  borderRadius:
                                  BorderRadius.circular(10),
                                ),
                                child:
                                Utils.buildSvgWithAssets(
                                  icon: AppAssets.bell,
                                  height: 24.h,
                                  width: 24.h,
                                  iconColor:
                                  AppColors.greyTextColor,
                                ),
                              ),
                              SizedBox(width: 12.h),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment:
                                  CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                        LocaleKeys.setReminder.tr(),
                                        style: TextStyle(
                                            fontSize: 14.f,
                                            fontWeight:
                                            FontWeight.w600,
                                            color: AppColors
                                                .textColor)),
                                    Text(
                                        LocaleKeys.notifyMeBeforeConsumptionTime.tr(),
                                        style: TextStyle(
                                          fontSize: 12.f,
                                          color: AppColors
                                              .textColorLight,
                                        )),
                                  ],
                                ),
                              ),
                              _buildToggle(med),
                            ],
                          ).paddingAll(16),
                        ),
                        Divider(
                            color: AppColors.greyColor),
                        _buildButtons(),
                      ],
                    ),
                  );
                },
              )
                  : Utils.getNoDataWidget(
                context,
                noDataText:
                LocaleKeys.noMedicationsToday.tr(),
              ),
            ),
          ),
        ],
      ).paddingAll(16),
    );
  }

  // medicine card
  Widget _buildMedHeader(ActivePrescriptionsResponseModel med) =>
      Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(12),
                child: Container(
                    width: 59.h,
                    height: 59.h,
                    decoration: RoundedRectangleBorder()
                        .toSmoothCornerDecoration(
                      color: AppColors.spacerLineColor,
                      borderRadius: 30.r,
                      hasShadow: false,
                    ),
                    child: Utils.buildImgWithNetwork(
                        url: med.productImageString ?? "",
                        iconColor: Colors.transparent)
                        .circle(52.h)),
              ),
              SizedBox(width: 12.h),
              Expanded(
                child: Text(
                  med.itemDescription ?? "",
                  style: TextStyle(
                      fontSize: 16.f,
                      fontWeight: FontWeight.w600,
                      color: AppColors.textColor),
                ),
              ),
            ]),
            SizedBox(height: 12.h),
            Wrap(
              spacing: 4,
              runSpacing: 4,
              children: [
                AppCustomChipWidget(
                    labelText:
                    LocaleKeys.route.tr(namedArgs: {LocaleKeys.route.tr(): med.route ?? ''})),
                AppCustomChipWidget(
                    labelText:
                    LocaleKeys.frequency.tr(namedArgs: {LocaleKeys.frequency.tr(): med.frequency ?? ''})),
                AppCustomChipWidget(
                    labelText:
                    LocaleKeys.instruction.tr(namedArgs: {LocaleKeys.instruction.tr(): med.doseDailyQuantity?.toString() ?? ''})),
                AppCustomChipWidget(
                    labelText:
                    LocaleKeys.duration.tr(namedArgs: {LocaleKeys.days.tr(): med.days.toString() ?? ''})),
              ],
            ),
          ],
        ),
      );

  Widget _buildButtons() => Padding(
    padding: EdgeInsets.all(16),
    child: Row(children: [
      Expanded(
        child: CustomButton(
          text: LocaleKeys.checkAvailability.tr(),
          fontSize: 13.f,
          onPressed: () {},
          backgroundColor: AppColors.secondaryLightRedColor,
          borderColor: AppColors.secondaryLightRedColor,
          textColor: AppColors.errorColor,
        ),
      ),
      SizedBox(width: 12.h),
      Expanded(
          child: CustomButton(
              text: LocaleKeys.readInstructions.tr(),
              fontSize: 13.f,
              onPressed: () {})),
    ]),
  );

  Widget _buildToggle(ActivePrescriptionsResponseModel med) {
    final medKey = _buildMedKey(med);
    final value = medReminderStatus[medKey] ?? false;

    return GestureDetector(
      onTap: () async {
        await showDoseDialog(med);
        final hasTime =
        (med.selectedDoseTimes).any((t) => t != null);
        medReminderStatus[medKey] = hasTime;
        await saveReminderStatus(medKey, hasTime);

        setState(() {});
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        width: 50.h,
        height: 28.h,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          color: value
              ? AppColors.lightGreenColor
              : AppColors.greyColor.withOpacity(0.3),
        ),
        child: AnimatedAlign(
          duration: const Duration(milliseconds: 200),
          alignment:
          value ? Alignment.centerRight : Alignment.centerLeft,
          child: Padding(
            padding: const EdgeInsets.all(3),
            child: Container(
              width: 22.h,
              height: 22.h,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: value
                    ? AppColors.textGreenColor
                    : AppColors.greyTextColor,
              ),
            ),
          ),
        ),
      ),
    );
  }


  Future<void> showDoseDialog(ActivePrescriptionsResponseModel med) {
    final doses = _getDosesCount(med);
    if (med.selectedDoseTimes.length != doses) {
      final old = med.selectedDoseTimes;
      med.selectedDoseTimes =
      List<String?>.filled(doses, null, growable: false);
      for (int i = 0; i < old.length && i < doses; i++) {
        med.selectedDoseTimes[i] = old[i];
      }
    }

    return showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (_) => Container(
        width: double.infinity,
        height: 520.h,
        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
          color: AppColors.bottomSheetBgColor,
          customBorder: const BorderRadius.only(
            topLeft: Radius.circular(24),
            topRight: Radius.circular(24),
          ),
          hasShadow: true,
        ),
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment:
                MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    LocaleKeys.reminders.tr(),
                    style: TextStyle(
                      fontSize: 20.f,
                      fontWeight: FontWeight.w600,
                      color: AppColors.textColor,
                    ),
                  ),
                  GestureDetector(
                    onTap: () => Navigator.pop(context),
                    child:  Utils.buildSvgWithAssets(
                      icon: AppAssets.close_bottom_sheet_icon,
                      height: 24.h,
                      width: 24.h,
                      iconColor:
                      AppColors.blackBgColor,
                    ),
                  ),
                ],
              ),
              SizedBox(height: 20.h),
              Expanded(
                child: ListView.builder(
                  itemCount: doses,
                  itemBuilder: (context, doseIndex) {
                    final badgeColor = [
                      AppColors.textGreenColor,
                      AppColors.infoColor,
                      AppColors.labelColorYellow,
                      AppColors.mainPurple
                    ][doseIndex % 4];
                    final doseLabel =
                        "${doseIndex + 1}${_getSuffix(doseIndex + 1)}";
                    final time =
                        med.selectedDoseTimes[doseIndex] ??
                            "Not set yet";
                    return GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                        showTimePickerSheet(med, doseIndex);
                      },
                      child: Container(
                        margin: const EdgeInsets.only(bottom: 12),
                        padding: const EdgeInsets.all(16),
                        decoration: RoundedRectangleBorder()
                            .toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 16.r,
                          hasShadow: false,
                        ),
                        child: Column(
                          crossAxisAlignment:
                          CrossAxisAlignment.start,
                          children: [
                            Container(
                              padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 14),
                              decoration: BoxDecoration(
                                color: badgeColor,
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: RichText(
                                text: TextSpan(
                                  children: [
                                    TextSpan(
                                      text: "${doseIndex + 1}",
                                      style: TextStyle(
                                        color: AppColors.whiteColor,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 16.f,
                                      ),
                                    ),
                                    WidgetSpan(
                                      child: Transform.translate(
                                        offset: const Offset(0, -4),
                                        child: Text(
                                          _getSuffix(doseIndex + 1),
                                          style: TextStyle(
                                            color: AppColors.whiteColor,
                                            fontSize: 10.f,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            SizedBox(height: 8.h),
                            Row(
                              mainAxisAlignment:
                              MainAxisAlignment.spaceBetween,
                              children: [
                                Expanded(
                                  child: Text(
                                    "Set reminder for $doseLabel dose",
                                    style: TextStyle(
                                      color: AppColors.textColor,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 16.f,
                                    ),
                                  ),
                                ),
                                Utils.buildSvgWithAssets(
                                  icon: AppAssets.arrow_forward,
                                  height: 24.h,
                                  width: 24.h,
                                  iconColor:
                                  AppColors.textColor,
                                ),
                              ],
                            ),
                            SizedBox(height: 4.h),
                            Text(
                              time,
                              style: TextStyle(
                                fontSize: 12.f,
                                color: AppColors.greyTextColor,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }


  void showTimePickerSheet(
      ActivePrescriptionsResponseModel med, int doseIndex) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (_) => Container(
        width: double.infinity,
        height: 460.h,
        decoration: BoxDecoration(
          color: AppColors.bottomSheetBgColor,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(24),
            topRight: Radius.circular(24),
          ),
        ),
        child: ReminderTimerDialog(
          med: med,
          frequencyNumber: _getDosesCount(med),
          doseIndex: doseIndex,
          onTimeSelected: (String time) async {
            final medKey = _buildMedKey(med);
            med.selectedDoseTimes[doseIndex] = time;
            await saveDoseTime(medKey, doseIndex, time);
            medReminderStatus[medKey] = true;
            await saveReminderStatus(medKey, true);
            setState(() {});
          },
        ),
      ),
    );
  }

  Widget buildDayCard(String label, DateTime date) {
    final isSelected = selectedDate.day == date.day &&
        selectedDate.month == date.month &&
        selectedDate.year == date.year;
    return GestureDetector(
      onTap: () {
        final vm =
        Provider.of<ActivePrescriptionsViewModel>(context,
            listen: false);
        setState(() {
          selectedDate = date;
          selectedDayMeds = vm.getMedsForSelectedDay(date);
        });
      },
      child: Container(
        width: 57.h,
        height: 65.h,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          color: isSelected
              ? AppColors.secondaryLightRedBorderColor
              : Colors.transparent,
          border: Border.all(
            color: isSelected
                ? AppColors.primaryRedBorderColor
                : AppColors.spacerLineColor,
            width: 1,
          ),
        ),
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  date.day == currentDate.day ? "Today" : label,
                  style: TextStyle(
                      color: isSelected
                          ? AppColors.primaryRedBorderColor
                          : AppColors.greyTextColor,
                      fontSize: 11.f,
                    fontWeight: FontWeight.w600,),
                ),
                SizedBox(height: 5.h),
                Text("${date.day}",
                    style: TextStyle(
                        fontSize: 16.f,
                        fontWeight: FontWeight.bold,
                        color: isSelected
                            ? AppColors.primaryRedBorderColor
                            : AppColors.textColor))
              ]),
        ),
      ),
    );
  }

  String _getSuffix(int day) {
    if (day == 1 || day == 21 || day == 31) return "st";
    if (day == 2 || day == 22) return "nd";
    if (day == 3 || day == 23) return "rd";
    return "th";
  }

}


class ReminderTimerDialog extends StatefulWidget {
  final int frequencyNumber;
  final int doseIndex;
  final Function(String) onTimeSelected;
  final ActivePrescriptionsResponseModel med;

  const ReminderTimerDialog({
    super.key,
    required this.frequencyNumber,
    required this.doseIndex,
    required this.onTimeSelected,
    required this.med,
  });

  @override
  State<ReminderTimerDialog> createState() => _ReminderTimerDialogState();
}

class _ReminderTimerDialogState extends State<ReminderTimerDialog> {
  TimeOfDay selectedTime = TimeOfDay.now();
  String? _selectedTime;
  String bigTimeText = "00:00";
  bool showPicker = false;

  CalenderUtilsNew calender =  CalenderUtilsNew.instance;

  final List<List<String>> presetTimes = [
    ["06:00 AM", "07:00 AM", "08:00 AM", "09:00 AM"], // Morning
    ["12:00 PM", "01:00 PM", "02:00 PM", "03:00 PM"], // Noon
    ["06:00 PM", "07:00 PM", "08:00 PM", "09:00 PM"], // Evening
  ];

  String _getSuffix(int number) {
    if (number == 1 || number == 21 || number == 31) return "st";
    if (number == 2 || number == 22) return "nd";
    if (number == 3 || number == 23) return "rd";
    return "th";
  }

  @override
  Widget build(BuildContext context) {
    final int bucket = widget.doseIndex.clamp(0, 2);
    final List<String> times = presetTimes[bucket];

    return Padding(
      padding: const EdgeInsets.all(16),
      child: Container(
        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
          color: AppColors.bottomSheetBgColor,
          customBorder: const BorderRadius.only(
            topLeft: Radius.circular(24),
            topRight: Radius.circular(24),
          ),
          hasShadow: true,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                RichText(
                  text: TextSpan(
                    children: [
                      TextSpan(
                        text: LocaleKeys.timeFor.tr(),
                        style: TextStyle(
                          fontSize: 18.f,
                          fontWeight: FontWeight.bold,
                          color: AppColors.textColor,
                        ),
                      ),
                      TextSpan(
                        text: "${widget.doseIndex + 1}",
                        style: TextStyle(
                          fontSize: 18.f,
                          fontWeight: FontWeight.bold,
                          color: AppColors.textColor,
                        ),
                      ),
                      WidgetSpan(
                        child: Transform.translate(
                          offset: const Offset(0, -6),
                          child: Text(
                            _getSuffix(widget.doseIndex + 1),
                            style: TextStyle(
                              fontSize: 12.f,
                              fontWeight: FontWeight.bold,
                              color: AppColors.textColor,
                            ),
                          ),
                        ),
                      ),
                      TextSpan(
                        text: LocaleKeys.reminder.tr(),
                        style: TextStyle(
                          fontSize: 18.f,
                          fontWeight: FontWeight.bold,
                          color: AppColors.textColor,
                        ),
                      ),
                    ],
                  ),
                ),
                    GestureDetector(
                      onTap: () => Navigator.pop(context),
                      child:Utils.buildSvgWithAssets(
                        icon: AppAssets.close_bottom_sheet_icon,
                        height: 24.h,
                        width: 24.h,
                        iconColor:
                        AppColors.blackBgColor,
                      ),),
              ],
            ),
            SizedBox(height: 12.h),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: times.map((t) {
                bool selected = _selectedTime == t;
                return AppCustomChipWidget(
                  labelText: t,
                  backgroundColor: selected
                      ? AppColors.lightGreenButtonColor
                      : AppColors.transparent,
                  textColor: AppColors.textColor,
                  shape: RoundedRectangleBorder(
                    side: BorderSide(
                      color: selected
                          ? AppColors.successColor
                          : AppColors.spacerLineColor,
                      width: 1.2,
                    ),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 14),
                  onChipTap: () {
                    setState(() {
                      _selectedTime = t;
                      selectedTime = _parseTime(t);
                      bigTimeText = selectedTime.format(context).split(" ")[0];
                      showPicker = false;
                    });
                  },
                );
              }).toList(),
            ),
            SizedBox(height: 25.h),
            GestureDetector(
              onTap: () {
                setState(() => showPicker = !showPicker);
              },
              child: Center(
                child: Column(
                  children: [
                    Text(
                      bigTimeText,
                      style: TextStyle(
                        fontSize: 48.f,
                        fontWeight: FontWeight.bold,
                        color: AppColors.textColor,
                      ),
                    ),
                    Text(
                      selectedTime.period == DayPeriod.am ? "AM" : "PM",
                      style: TextStyle(
                        fontSize: 20.f,
                        fontWeight: FontWeight.bold,
                        color: AppColors.greyTextColor,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(height: 15.h),
            if (showPicker)
              SizedBox(
                height: 100.h,
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.time,
                  use24hFormat: false,
                  initialDateTime: DateTime(
                    2024,
                    1,
                    1,
                    selectedTime.hour,
                    selectedTime.minute,
                  ),
                  onDateTimeChanged: (newTime) {
                    setState(() {
                      _selectedTime = null;
                      selectedTime = TimeOfDay(hour: newTime.hour, minute: newTime.minute);
                      bigTimeText = selectedTime.format(context).split(" ")[0];
                    });
                  },
                ),
              ),
            SizedBox(height: 25.h),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColors.successColor,
                      foregroundColor: AppColors.whiteColor,
                      elevation: 0,
                      padding: const EdgeInsets.symmetric(vertical: 14),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                    onPressed: () async {
                      final selectedFormattedTime = selectedTime.format(context);
                      widget.onTimeSelected(selectedFormattedTime);
                      try {
                        final parts = selectedFormattedTime.split(":");
                        int hour = int.parse(parts[0]);
                        int minute = int.parse(parts[1].split(" ")[0]);
                        bool isPM = selectedFormattedTime.contains("PM");
                        if (isPM && hour != 12) hour += 12;
                        if (!isPM && hour == 12) hour = 0;
                        int totalMinutes = hour * 60 + minute;

                        await calender.createMultipleEvents(
                          reminderMinutes: totalMinutes,
                          frequencyNumber: widget.frequencyNumber,
                          days: widget.med.days ?? 1,
                          orderDate: widget.med.orderDate ?? "",
                          itemDescriptionN: widget.med.itemDescription ?? "",
                          route: widget.med.route ?? "",
                          onFailure: (errorMessage) {},
                          prescriptionNumber: widget.med.itemId.toString()
                        );

                        // await setCalender(
                        //   context,
                        //   eventId: widget.med.itemId.toString(),
                        //   selectedMinutes: totalMinutes,
                        //   frequencyNumber: widget.frequencyNumber,
                        //   days: widget.med.days ?? 1,
                        //   orderDate: widget.med.orderDate ?? "",
                        //   itemDescriptionN: widget.med.itemDescription ?? "",
                        //   route: widget.med.route ?? "",
                        // );
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(content: Text(LocaleKeys.reminderAddedToCalendar.tr())),
                        );
                      } catch (e) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(content: Text(LocaleKeys.errorWhileSettingCalendar.tr(namedArgs: {'error': e.toString()}))),
                        );
                      }
                      Navigator.pop(context);
                    },
                    child: Text(
                      LocaleKeys.save.tr(),
                      style: TextStyle(
                        fontWeight: FontWeight.w600,
                        fontSize: 16.f,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ).paddingAll(16),
      ),
    );
  }

  TimeOfDay _parseTime(String t) {
    try {
      int hour = int.parse(t.split(":")[0]);
      int minute = int.parse(t.split(":")[1].split(" ")[0]);
      bool pm = t.contains("PM");
      if (pm && hour != 12) hour += 12;
      if (!pm && hour == 12) hour = 0;
      return TimeOfDay(hour: hour, minute: minute);
    } catch (_) {
      return TimeOfDay.now();
    }
  }
}






