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/app_state.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/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/route_extensions.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/presentation/prescriptions/prescription_ai_analysis_detailed_page.dart';
import 'package:hmg_patient_app_new/presentation/prescriptions/prescription_item_view.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/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:open_filex/open_filex.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

import 'dart:ui' as ui;

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

  PatientPrescriptionsResponseModel prescriptionsResponseModel;
  bool isFromAppointments = false;

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

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


  @override
  void initState() {
    // locationUtils = new LocationUtils(isShowConfirmDialog: true, context: context);
    // WidgetsBinding.instance.addPostFrameCallback((_) => locationUtils.getCurrentLocation());
    if (!widget.isFromAppointments) {
      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: widget.prescriptionsResponseModel.isInOutPatient ?? false
                  ? () async {
                      LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingPrescriptionPDFPleaseWait.tr(context: context));
                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"),
                      callBackFunc: () {},
                      isFullScreen: false,
                      isCloseButtonVisible: true,
                    );
                  }
                }, onError: (err) {
                  LoaderBottomSheet.hideLoader();
                  showCommonBottomSheetWithoutHeight(
                    context,
                    child: Utils.getErrorWidget(loadingText: err),
                    callBackFunc: () {},
                    isFullScreen: false,
                    isCloseButtonVisible: true,
                  );
                });
                    }
                  : null,
              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: [
                              AppCustomChipWidget(
                                labelText: getIt.get<AppState>().isArabic()
                                    ? (widget.prescriptionsResponseModel.isInOutPatientDescriptionN ?? "العيادات الخارجية")
                                    : (widget.prescriptionsResponseModel.isInOutPatientDescription ?? "OutPatient"),
                                backgroundColor: AppColors.warningColorYellow.withOpacity(0.1),
                                textColor: AppColors.warningColorYellow,
                              ),
                              SizedBox(height: 16.h),
                              Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Utils.buildImgWithNetwork(
                                    url: widget.prescriptionsResponseModel.doctorImageURL!,
                                    iconColor: AppColors.blackBgColor,
                                    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: [
                                  Directionality(
                                    textDirection: ui.TextDirection.ltr,
                                    child: AppCustomChipWidget(
                                      icon: AppAssets.doctor_calendar_icon,
                                      labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(widget.prescriptionsResponseModel.appointmentDate), false),
                                      isEnglishOnly: true
                                      ,
                                      labelPadding: EdgeInsetsDirectional.only(start: -4.h, end: 8.h),
                                    ),
                                  ),
                                  AppCustomChipWidget(
                                    labelText: widget.prescriptionsResponseModel.clinicDescription!,
                                  ),
                                  AppCustomChipWidget(
                                    icon: AppAssets.rating_icon,
                                    iconColor: AppColors.ratingColorYellow,
                                    labelText: LocaleKeys.ratingValue.tr(namedArgs: {'rating': widget.prescriptionsResponseModel.decimalDoctorRate.toString()}, context: context),
                                    isEnglishOnly: true,
                                  ),
                                  AppCustomChipWidget(
                                    labelText: widget.prescriptionsResponseModel.name ?? "",
                                  ),
                                ],
                              ),
                              SizedBox(height: 16.h),
                              CustomButton(
                                text: LocaleKeys.downloadPrescription.tr(context: context),
                                onPressed: () async {
                                  LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingPrescriptionPDFPleaseWait.tr(context: context));
                                  await prescriptionVM.getPrescriptionPDFBase64(widget.prescriptionsResponseModel, onSuccess: (value) 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"),
                                          callBackFunc: () {},
                                          isFullScreen: false,
                                          isCloseButtonVisible: true,
                                        );
                                      }
                                    }
                                  }, onError: (err) {
                                    LoaderBottomSheet.hideLoader();
                                    showCommonBottomSheetWithoutHeight(
                                      context,
                                      child: Utils.getErrorWidget(loadingText: err),
                                      callBackFunc: () {},
                                      isFullScreen: false,
                                      isCloseButtonVisible: true,
                                    );
                                  });
                                },
                                backgroundColor: AppColors.successColor.withValues(alpha: 0.15),
                                borderColor: AppColors.successColor.withValues(alpha: 0.01),
                                textColor: AppColors.successColor,
                                fontSize: 14.f,
                                fontWeight: FontWeight.w600,
                                borderRadius: 12.r,
                                padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                height: 40.h,
                                icon: AppAssets.download,
                                iconColor: AppColors.successColor,
                                iconSize: 14.h,
                              ),
                            ],
                          ),
                        ),
                      ).paddingSymmetrical(24.h, 0.h),
                      SizedBox(height: 16.h),
                      ListView.builder(
                        shrinkWrap: true,
                        padding: EdgeInsets.zero,
                        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: Column(
           children: [
             SizedBox(height: 24.h),
             Container(

            child: CustomButton(
              text: widget.prescriptionsResponseModel.isHomeMedicineDeliverySupported! ? LocaleKeys.resendOrder.tr(context: context) : LocaleKeys.prescriptionDeliveryError.tr(context: context),
              onPressed: () async {
                if (widget.prescriptionsResponseModel.isHomeMedicineDeliverySupported!) {
                  LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingPrescriptionDetails.tr(context: context));
                  await prescriptionsViewModel.getPrescriptionDetails(widget.prescriptionsResponseModel, onSuccess: (val) {
                    LoaderBottomSheet.hideLoader();
                    prescriptionsViewModel.initiatePrescriptionDelivery(context);
                  }, onError: (err) {
                    LoaderBottomSheet.hideLoader();
                    print(err);
                  });
                }
              },
              backgroundColor: widget.prescriptionsResponseModel.isHomeMedicineDeliverySupported! ? AppColors.successColor : AppColors.textColor.withOpacity(0.15),
              borderColor: AppColors.successColor.withOpacity(0.01),
              textColor: widget.prescriptionsResponseModel.isHomeMedicineDeliverySupported! ? Colors.white : AppColors.textColor.withOpacity(0.35),
              fontSize: 16,
              fontWeight: FontWeight.w600,
              borderRadius: 12,
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              height: 56.h,
              icon: AppAssets.prescription_refill_icon,
              iconColor: widget.prescriptionsResponseModel.isHomeMedicineDeliverySupported! ? Colors.white : AppColors.textColor.withOpacity(0.35),
              iconSize: 20.h,
            ).paddingSymmetrical(24.h, 0.h),
          ),

             Utils.havePrivilege(119) ?  Container(
                 child: Container(
                   height: 56.h,
                   decoration: BoxDecoration(
                     borderRadius: BorderRadius.circular(14.r),
                     gradient: LinearGradient(
                       begin: Alignment.centerLeft,
                       end: Alignment.centerRight,
                       stops: [0.236, 1.0],
                       colors: [
                         Color(0xFF8A38F5),
                         Color(0xFFE20BBB),
                       ],
                     ),
                   ),
                   child: Row(
                     crossAxisAlignment: CrossAxisAlignment.center,
                     mainAxisAlignment: MainAxisAlignment.center,
                     children: [
                       Padding(
                         padding: EdgeInsets.only(right: 4.w, left: 4.w),
                         child: Utils.buildSvgWithAssets(icon: AppAssets.aiOverView, width: 16.h, height: 16.h, iconColor: Colors.white),
                       ),
                       LocaleKeys.generateAiAnalysisPrescription.tr(context: context).toText16(isBold: true, color: Colors.white)
                     ],
                   ),
                 ).paddingSymmetrical(24.h, 12.h).onPress(() {
                   final _dialogService = getIt.get<DialogService>();
                   _dialogService.showCommonBottomSheetWithoutH(
                       message: LocaleKeys.aiDisclaimerPrescription.tr(),
                       label: LocaleKeys.consent.tr(),
                       okLabel: LocaleKeys.acceptLbl.tr(),
                       cancelLabel: LocaleKeys.rejectView.tr(),
                       onOkPressed: () {
                         context.pop();
                         prescriptionsViewModel.setIsPrescriptionAIAnalysisNeedsToBeShown(true);
                         prescriptionsViewModel.getPrescriptionAiAnalysis(
                           prescriptions: prescriptionsViewModel.prescriptionDetailsList,
                           langId: getIt.get<AppState>().getLanguageID(),
                           loadingText: LocaleKeys.loadingAIAnalysisPrescription.tr(context: context),
                           onNavigate: (data) {
                             // Navigate to prescription AI analysis detailed page
                             Navigator.push(
                               context,
                               CustomPageRoute(
                                 direction: AxisDirection.down,
                                 page: PrescriptionAiAnalysisDetailedPage(),
                               ),
                             );
                           },
                         );
                       },
                       onCancelPressed: () {
                         context.pop();
                       });
                 }),

             ): SizedBox(height: 24,),
        ]))
        ],
      ),
    );
  }
}
