import 'dart:io' show Platform;

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/utils/calender_utils_new.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/prescriptions/prescriptions_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/services/permission_service.dart';
import 'package:hmg_patient_app_new/theme/colors.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/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/scroll_wheel_time_picker.dart';
import 'package:permission_handler/permission_handler.dart';

class PrescriptionItemView extends StatelessWidget {
  int index;
  PrescriptionsViewModel prescriptionVM;
  bool isLoading;

  PrescriptionItemView({Key? key, required this.prescriptionVM, required this.index, this.isLoading = false}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      duration: Duration(milliseconds: 300),
      curve: Curves.easeInOut,
      margin: EdgeInsets.symmetric(vertical: 8.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 20.h, hasShadow: true),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 16.h),
          Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.start,
            spacing: 8.h,
            children: [
              Utils.buildImgWithNetwork(
                url: isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].imageThumbUrl!,
                iconColor: AppColors.blackBgColor,
                width: 60.h,
                height: 60.h,
                errorBuilder: (cxt, child, tr) {
                  return SizedBox(height: 60, width: 60);
                },
                fit: BoxFit.fill,
              ).toShimmer2(isShow: isLoading).circle(100),
              Expanded(
                child: (isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].itemDescription!).toText16(isBold: true, maxlines: 2, isEnglishOnly: true).toShimmer2(isShow: isLoading),
              ),
            ],
          ).paddingSymmetrical(16.h, 0.h),
          SizedBox(height: 16.h),
          Wrap(
            direction: Axis.horizontal,
            spacing: 6.h,
            runSpacing: 6.h,
            children: [
              AppCustomChipWidget(
                labelText: "${LocaleKeys.routePrescription.tr(context: context)}: ${isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].route}",
              ).toShimmer2(isShow: isLoading),
              AppCustomChipWidget(
                labelText: "${LocaleKeys.frequency.tr(context: context)}: ${isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].frequency}",
              ).toShimmer2(isShow: isLoading),
              AppCustomChipWidget(
                labelText: "${LocaleKeys.dailyDoses.tr(context: context)}: ${isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].doseDailyQuantity}",
              ).toShimmer2(isShow: isLoading),
              AppCustomChipWidget(
                labelText: "${LocaleKeys.days.tr(context: context)}: ${isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].days}",
                isEnglishOnly: true,
              ).toShimmer2(isShow: isLoading),
            ],
          ).paddingSymmetrical(16.h, 0.h),
          SizedBox(height: 8.h),
          if (!isLoading)
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Utils.buildSvgWithAssets(icon: AppAssets.prescription_remarks_icon, width: 18.h, height: 18.h),
                SizedBox(width: 9.h),
                Expanded(
                  child: "${LocaleKeys.remarks.tr(context: context)} ${isLoading ? "" : prescriptionVM.prescriptionDetailsList[index].remarks!}".toText10(isBold: true, isEnglishOnly: true),
                ),
              ],
            ).paddingSymmetrical(16.h, 0.h),
          SizedBox(height: 14.h),
          Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h),
          SizedBox(height: 14.h),
          Visibility(
            visible: (!isLoading && prescriptionVM.prescriptionDetailsList[index].frequencyNumber != 0),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              children: [
                Utils.buildSvgWithAssets(icon: AppAssets.prescription_reminder_icon, width: 35.h, height: 35.h, applyThemeColor: false).toShimmer2(isShow: isLoading),
                SizedBox(width: 8.h),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    LocaleKeys.setReminder.tr(context: context).toText13(isBold: true),
                    LocaleKeys.notifyPrescription.tr(context: context).toText10(color: AppColors.textColorLight),
                  ],
                ).toShimmer2(isShow: isLoading).expanded,
                Switch(
                  activeColor: AppColors.successColor,
                  activeTrackColor: AppColors.successColor.withValues(alpha: .15),
                  value: isLoading ? false : prescriptionVM.prescriptionDetailsList[index].hasReminder!,
                  // value: prescriptionVM.prescriptionDetailsList[index].hasReminder ?? false,
                  onChanged: (newValue) async {
                    CalenderUtilsNew calender = CalenderUtilsNew.instance;
                    if (await prescriptionVM.checkIfReminderExistForPrescription(index)) {
                      prescriptionVM.prescriptionDetailsList[index].hasReminder = true;

                      LoaderBottomSheet.showLoader(loadingText: "Removing Reminders");
                      bool resultValue = await calender.checkAndRemoveMultipleItems(id: prescriptionVM.prescriptionDetailsList[index].itemID.toString());

                      prescriptionVM.setPrescriptionItemReminder(newValue, prescriptionVM.prescriptionDetailsList[index]);
                      LoaderBottomSheet.hideLoader();
                      return;
                    } else {
                      DateTime startDate = DateTime.now();
                      prescriptionVM.serSelectedTime(startDate);
                      DateTime endDate = DateTime(startDate.year, startDate.month, startDate.day + prescriptionVM.prescriptionDetailsList[index].days!.toInt());
                      showCommonBottomSheetWithoutHeight(context, child: bottomSheetContent(context), title: LocaleKeys.timeForFirstReminder.tr(), isCloseButtonVisible: true);

                      // BottomSheetUtils().showReminderBottomSheet(
                      //   context,
                      //   endDate,
                      //   "",
                      //   prescriptionVM.prescriptionDetailsList[index].itemID.toString(),
                      //   "",
                      //   "",
                      //   title: "${prescriptionVM.prescriptionDetailsList[index].itemDescription} Prescription Reminder",
                      //   description:
                      //       "${prescriptionVM.prescriptionDetailsList[index].itemDescription} ${prescriptionVM.prescriptionDetailsList[index].frequency} ${prescriptionVM.prescriptionDetailsList[index].route} ",
                      //   onSuccess: () {},
                      //   isMultiAllowed: true,
                      //   onMultiDateSuccess: (int selectedIndex) async {
                      //     bool isEventAdded = await calender.createMultipleEvents(
                      //       reminderMinutes: selectedIndex,
                      //       frequencyNumber: prescriptionVM.prescriptionDetailsList[index].frequencyNumber?.toInt(),
                      //       days: prescriptionVM.prescriptionDetailsList[index].days!.toInt(),
                      //       orderDate: prescriptionVM.prescriptionDetailsList[index].orderDate!,
                      //       itemDescriptionN: prescriptionVM.prescriptionDetailsList[index].itemDescription!,
                      //       route: prescriptionVM.prescriptionDetailsList[index].route!,
                      //       onFailure: (errorMessage) => prescriptionVM.showError(errorMessage),
                      //       prescriptionNumber: prescriptionVM.prescriptionDetailsList[index].itemID.toString(),
                      //     );
                      //     prescriptionVM.setPrescriptionItemReminder(isEventAdded, prescriptionVM.prescriptionDetailsList[index]);
                      //     // setCalender(context,
                      //     //     eventId: prescriptionVM.prescriptionDetailsList[index].itemID.toString(),
                      //     //     selectedMinutes: selectedIndex,
                      //     //     frequencyNumber: prescriptionVM.prescriptionDetailsList[index].frequencyNumber?.toInt(),
                      //     //     days: prescriptionVM.prescriptionDetailsList[index].days!.toInt(),
                      //     //     orderDate: prescriptionVM.prescriptionDetailsList[index].orderDate!,
                      //     //     itemDescriptionN: prescriptionVM.prescriptionDetailsList[index].itemDescription!,
                      //     //     route: prescriptionVM.prescriptionDetailsList[index].route!);
                      //   },
                      // );
                    }
                  },
                ).toShimmer2(isShow: isLoading),
              ],
            ).paddingSymmetrical(16.h, 0.h),
          ),
          SizedBox(height: 14.h),
          // Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h),
          // Row(
          //   children: [
          //     Expanded(
          //       child: CustomButton(
          //         text: LocaleKeys.checkAvailability.tr(context: context),
          //         onPressed: () {},
          //         backgroundColor: AppColors.primaryRedColor.withOpacity(0.1),
          //         borderColor: AppColors.primaryRedColor.withOpacity(0.0),
          //         textColor: AppColors.primaryRedColor,
          //         fontSize: 14.f,
          //         isBold: true,
          //         borderRadius: 12.r,
          //         padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
          //         height: 40.h,
          //       ).toShimmer2(isShow: isLoading),
          //     ),
          //     // SizedBox(width: 16.h),
          //   ],
          // ).paddingSymmetrical(16.h, 16.h),
        ],
      ),
    );
  }

  Widget bottomSheetContent(BuildContext context) {
    return Column(
      children: [
        SizedBox(height: 4.h),
        LocaleKeys.reminderRemovalNote.tr().toText14(isBold: true, color: AppColors.warningColorYellow),
        SizedBox(height: 8.h),
        ScrollWheelTimePicker(
          initialHour: DateTime.now().hour,
          initialMinute: DateTime.now().minute,
          use24HourFormat: true,
          pickerHeight: 200.h,
          itemExtent: 100.h,
          onTimeChanged: (time) {
            // Handle selected time
            debugPrint('Selected time: ${time.hour}:${time.minute}');
            prescriptionVM.serSelectedTime(DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, time.hour, time.minute));
          },
        ),
        SizedBox(height: 8.h),
        CustomButton(
            backgroundColor: AppColors.successColor,
            borderColor: AppColors.successColor,
            text: LocaleKeys.add.tr(),
            onPressed: () async {
              CalenderUtilsNew calender = CalenderUtilsNew.instance;
              bool isEventAdded = await calender.createMultipleEvents(
                reminderMinutes: 10,
                  scaleOffset : prescriptionVM.prescriptionDetailsList[index].scaleOffset!,
                frequencyNumber: prescriptionVM.prescriptionDetailsList[index].frequencyNumber?.toInt(),
                days: prescriptionVM.prescriptionDetailsList[index].days!.toInt(),
                orderDate: prescriptionVM.prescriptionDetailsList[index].orderDate!,
                itemDescriptionN: prescriptionVM.prescriptionDetailsList[index].itemDescription!,
                route: prescriptionVM.prescriptionDetailsList[index].route!,
                onFailure: (errorMessage) => prescriptionVM.showError(errorMessage),
                prescriptionNumber: prescriptionVM.prescriptionDetailsList[index].itemID.toString(),
                scheduleDateTime: prescriptionVM.selectedReminderTime,
              );
              prescriptionVM.setPrescriptionItemReminder(isEventAdded, prescriptionVM.prescriptionDetailsList[index]);
              Navigator.of(context).pop();
            })
      ],
    );
  }

  /// Checks and requests calendar permissions for both Android and iOS
  /// Returns true if all required permissions are granted
  Future<bool> _checkAndRequestCalendarPermissions() async {
    if (Platform.isAndroid) {
      // Android: Check existing permission first using PermissionService
      bool hasPermission = await PermissionService.isCalendarPermissionEnabled();
      if (hasPermission) {
        return true;
      }

      // Request calendarFullAccess permission (Android 14+ requires this)
      // This internally requests both READ_CALENDAR and WRITE_CALENDAR
      PermissionStatus status = await Permission.calendarFullAccess.request();

      // If calendarFullAccess request didn't show dialog or failed,
      // fallback to requesting individual permissions
      if (!status.isGranted) {
        Map<Permission, PermissionStatus> statuses = await [
          Permission.calendarWriteOnly,
        ].request();

        return statuses[Permission.calendarWriteOnly]?.isGranted ?? false;
      }

      return status.isGranted;
    } else {
      // iOS: Check if we already have full access
      PermissionStatus fullAccessStatus = await Permission.calendarFullAccess.status;

      if (fullAccessStatus.isGranted) {
        return true;
      }

      // Request write permission first (required before full access on iOS)
      PermissionStatus writeStatus = await Permission.calendarWriteOnly.request();
      if (!writeStatus.isGranted) {
        return false;
      }

      // Then request full access permission
      PermissionStatus fullStatus = await Permission.calendarFullAccess.request();
      return fullStatus.isGranted;
    }
  }

  /// Shows permission denied dialog with option to open settings
  Future<void> _showPermissionDeniedDialog(BuildContext context) async {
    showCommonBottomSheetWithoutHeight(
      context,
      title: LocaleKeys.notice.tr(context: context),
      child: Utils.getWarningWidget(
        loadingText: LocaleKeys.calendarPermissionAlert.tr(),
        isShowActionButtons: true,
        onCancelTap: () {
          Navigator.of(context).pop();
        },
        onConfirmTap: () async {
          Navigator.of(context).pop();
          await openAppSettings();
        },
      ),
      callBackFunc: () {},
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }
}
