import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/utils/calendar_utils.dart';
import 'package:hmg_patient_app_new/core/utils/date_util.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/prescriptions/models/resp_models/patient_prescriptions_response_model.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/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/presentation/prescriptions/prescription_item_view.dart';
import 'package:hmg_patient_app_new/presentation/prescriptions/prescription_reminder_view.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/shimmer/movies_shimmer_widget.dart';
import 'package:open_filex/open_filex.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

class PrescriptionDetailPage extends StatefulWidget {
  PrescriptionDetailPage({super.key, required this.prescriptionsResponseModel});

  PatientPrescriptionsResponseModel prescriptionsResponseModel;

  @override
  State<PrescriptionDetailPage> createState() => _PrescriptionDetailPageState();
}

class _PrescriptionDetailPageState extends State<PrescriptionDetailPage> {
  late PrescriptionsViewModel prescriptionsViewModel;

  bool _isSwitched = false; // Initial state of the switch

  @override
  void initState() {
    checkAndRemove(false);
    // locationUtils = new LocationUtils(isShowConfirmDialog: true, context: context);
    // WidgetsBinding.instance.addPostFrameCallback((_) => locationUtils.getCurrentLocation());
    scheduleMicrotask(() {
      prescriptionsViewModel.setPrescriptionsDetailsLoading();
      prescriptionsViewModel.getPrescriptionDetails(widget.prescriptionsResponseModel);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    prescriptionsViewModel = Provider.of<PrescriptionsViewModel>(context, listen: false);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              title: LocaleKeys.prescriptions.tr(context: context),
              instructions: () async {
                LoaderBottomSheet.showLoader(loadingText: "Fetching prescription PDF, Please wait...".needTranslation);
                await prescriptionsViewModel.getPrescriptionInstructionsPDF(widget.prescriptionsResponseModel, onSuccess: (val) {
                  LoaderBottomSheet.hideLoader();
                  if (prescriptionsViewModel.prescriptionInstructionsPDFLink.isNotEmpty) {
                    Uri uri = Uri.parse(prescriptionsViewModel.prescriptionInstructionsPDFLink);
                    launchUrl(uri, mode: LaunchMode.platformDefault, webOnlyWindowName: "");
                  } else {
                    showCommonBottomSheetWithoutHeight(
                      context,
                      child: Utils.getErrorWidget(loadingText: "Unable to fetch PDF".needTranslation),
                      callBackFunc: () {},
                      isFullScreen: false,
                      isCloseButtonVisible: true,
                    );
                  }
                }, onError: (err) {
                  LoaderBottomSheet.hideLoader();
                  showCommonBottomSheetWithoutHeight(
                    context,
                    child: Utils.getErrorWidget(loadingText: err),
                    callBackFunc: () {},
                    isFullScreen: false,
                    isCloseButtonVisible: true,
                  );
                });
              },
              child: SingleChildScrollView(
                child: Consumer<PrescriptionsViewModel>(builder: (context, prescriptionVM, child) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: 24.h),
                      Container(
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 20.h,
                          hasShadow: true,
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(16.h),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Image.network(
                                    widget.prescriptionsResponseModel.doctorImageURL!,
                                    width: 24.h,
                                    height: 24.h,
                                    fit: BoxFit.fill,
                                  ).circle(100),
                                  SizedBox(width: 8.h),
                                  Expanded(child: widget.prescriptionsResponseModel.doctorName!.toText16(isBold: true)),
                                ],
                              ),
                              SizedBox(height: 16.h),
                              Wrap(
                                direction: Axis.horizontal,
                                spacing: 4.h,
                                runSpacing: 4.h,
                                children: [
                                  AppCustomChipWidget(
                                    icon: AppAssets.doctor_calendar_icon,
                                    labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(widget.prescriptionsResponseModel.appointmentDate), false),
                                    labelPadding: EdgeInsetsDirectional.only(start: -4.h, end: 8.h),
                                  ),
                                  AppCustomChipWidget(
                                    labelText: widget.prescriptionsResponseModel.clinicDescription!,
                                  ),
                                  AppCustomChipWidget(
                                    icon: AppAssets.rating_icon,
                                    iconColor: AppColors.ratingColorYellow,
                                    labelText: "Rating: ${widget.prescriptionsResponseModel.decimalDoctorRate}".needTranslation,
                                  ),
                                  AppCustomChipWidget(
                                    labelText: widget.prescriptionsResponseModel.name!,
                                  ),
                                ],
                              ),
                              SizedBox(height: 16.h),
                              CustomButton(
                                text: "Download Prescription".needTranslation,
                                onPressed: () async {
                                  LoaderBottomSheet.showLoader();
                                  await prescriptionVM.getPrescriptionPDFBase64(widget.prescriptionsResponseModel).then((val) async {
                                    LoaderBottomSheet.hideLoader();
                                    if (prescriptionVM.prescriptionPDFBase64Data.isNotEmpty) {
                                      String path = await Utils.createFileFromString(prescriptionVM.prescriptionPDFBase64Data, "pdf");
                                      try {
                                        OpenFilex.open(path);
                                      } catch (ex) {
                                        showCommonBottomSheetWithoutHeight(
                                          context,
                                          child: Utils.getErrorWidget(loadingText: "Cannot open file".needTranslation),
                                          callBackFunc: () {},
                                          isFullScreen: false,
                                          isCloseButtonVisible: true,
                                        );
                                      }
                                    }
                                  });
                                },
                                backgroundColor: AppColors.successColor.withValues(alpha: 0.15),
                                borderColor: AppColors.successColor.withValues(alpha: 0.01),
                                textColor: AppColors.successColor,
                                fontSize: 14,
                                fontWeight: FontWeight.w500,
                                borderRadius: 12,
                                padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                height: 40.h,
                                icon: AppAssets.download,
                                iconColor: AppColors.successColor,
                                iconSize: 14.h,
                              ),
                            ],
                          ),
                        ),
                      ).paddingSymmetrical(24.h, 0.h),
                      ListView.builder(
                        shrinkWrap: true,
                        physics: NeverScrollableScrollPhysics(),
                        itemCount: prescriptionVM.isPrescriptionsDetailsLoading ? 5 : prescriptionVM.prescriptionDetailsList.length,
                        itemBuilder: (context, index) {
                          return prescriptionVM.isPrescriptionsDetailsLoading
                              ? PrescriptionItemView(prescriptionVM: prescriptionVM, index: index, isLoading: true)
                              : AnimationConfiguration.staggeredList(
                                  position: index,
                                  duration: const Duration(milliseconds: 500),
                                  child: SlideAnimation(
                                    verticalOffset: 100.0,
                                    child: FadeInAnimation(
                                      child: PrescriptionItemView(prescriptionVM: prescriptionVM, index: index),
                                    ),
                                  ),
                                );
                        },
                      ).paddingSymmetrical(24.h, 0.h),
                    ],
                  );
                }),
              ),
            ),
          ),
          Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 24.h,
              hasShadow: true,
            ),
            child: CustomButton(
              text: widget.prescriptionsResponseModel.isHomeMedicineDeliverySupported! ? LocaleKeys.resendOrder.tr(context: context) : LocaleKeys.prescriptionDeliveryError.tr(context: context),
              onPressed: () {},
              backgroundColor: widget.prescriptionsResponseModel.isHomeMedicineDeliverySupported! ? AppColors.successColor : AppColors.greyF7Color,
              borderColor: AppColors.successColor.withOpacity(0.01),
              textColor: widget.prescriptionsResponseModel.isHomeMedicineDeliverySupported! ? AppColors.whiteColor : AppColors.textColor.withOpacity(0.35),
              fontSize: 16,
              fontWeight: FontWeight.w500,
              borderRadius: 12,
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              height: 50.h,
              icon: AppAssets.prescription_refill_icon,
              iconColor: widget.prescriptionsResponseModel.isHomeMedicineDeliverySupported! ? AppColors.whiteColor : AppColors.textColor.withOpacity(0.35),
              iconSize: 20.h,
            ).paddingSymmetrical(24.h, 24.h),
          ),
        ],
      ),
    );
  }
}
