import 'package:easy_localization/easy_localization.dart' show tr, StringTranslateExtension;
import 'package:flutter/material.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/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/lab/lab_view_model.dart';
import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_order_response_by_ai_model.dart';
import 'package:hmg_patient_app_new/features/lab/models/resp_models/patient_lab_orders_response_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/LabResultList.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/ai_analysis_widget.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/lab_order_specialResult.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/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:open_filex/open_filex.dart';
import 'package:provider/provider.dart';

class LabResultByClinic extends StatelessWidget {
  LabResultByClinic({required this.labOrder, Key? key});

  late LabViewModel labViewModel;
  PatientLabOrdersResponseModel labOrder;

  @override
  Widget build(BuildContext context) {
    labViewModel = Provider.of<LabViewModel>(context, listen: false);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
                title: LocaleKeys.labResults.tr(),
                downloadReport: () async {
                  LoaderBottomSheet.showLoader(loadingText: LocaleKeys.generatingReport.tr(context: context));
                  await labViewModel
                      .getLabResultReportPDF(
                          labOrder: labOrder,
                          onError: (err) {
                            LoaderBottomSheet.hideLoader();
                            showCommonBottomSheetWithoutHeight(
                              context,
                              child: Utils.getErrorWidget(loadingText: err),
                              callBackFunc: () {},
                              isFullScreen: false,
                              isCloseButtonVisible: true,
                            );
                          })
                      .then((val) async {
                    LoaderBottomSheet.hideLoader();
                    if (labViewModel.patientLabResultReportPDFBase64.isNotEmpty) {
                      String path = await Utils.createFileFromString(labViewModel.patientLabResultReportPDFBase64, "pdf");
                      try {
                        OpenFilex.open(path);
                      } catch (ex) {
                        showCommonBottomSheetWithoutHeight(
                          context,
                          child: Utils.getErrorWidget(loadingText: "Cannot open file"),
                          callBackFunc: () {},
                          isFullScreen: false,
                          isCloseButtonVisible: true,
                        );
                      }
                    }
                  });
                },
                // aiOverview: () async {
                //   final _dialogService = getIt.get<DialogService>();
                //   await _dialogService.showCommonBottomSheetWithoutH(
                //       message: LocaleKeys.aiDisclaimer.tr(),
                //       label: LocaleKeys.consent.tr(),
                //       okLabel: LocaleKeys.acceptLbl.tr(),
                //       cancelLabel: LocaleKeys.rejectView.tr(),
                //       onOkPressed: () {
                //         context.pop();
                //         labViewModel.getAiOverviewLabOrders(labOrder: labOrder, loadingText: LocaleKeys.loadingAIAnalysis.tr(context: context));
                //       },
                //       onCancelPressed: () {
                //         context.pop();
                //       });
                // },
                child: SingleChildScrollView(
                  child: Column(
                    spacing: 8.h,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Selector<LabViewModel, bool>(
                        selector: (_, model) => model.isLabResultByHospitalLoading,
                        builder: (_, isLoading, __) {
                          if (isLoading) {
                            return Column(
                              children: [
                                LabResultItemView(
                                  onTap: () {},
                                  labOrder: null,
                                  index: 0,
                                  isLoading: true,
                                ),
                                LabResultItemView(
                                  onTap: () {},
                                  labOrder: null,
                                  index: 0,
                                  isLoading: true,
                                ),
                                LabResultItemView(
                                  onTap: () {},
                                  labOrder: null,
                                  index: 0,
                                  isLoading: true,
                                ),
                                LabResultItemView(
                                  onTap: () {},
                                  labOrder: null,
                                  index: 0,
                                  isLoading: true,
                                ),
                              ],
                            );
                          } else {
                            return LabResultList();
                          }
                        },
                      ),
                      LabOrderSpecialResult(),
                    ],
                  ).paddingAll(24.h),
                )),
          ),
          Utils.havePrivilege(115)
              ? Container(
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                    color: AppColors.whiteColor,
                    borderRadius: 24.h,
                    hasShadow: true,
                  ),
                  child: Container(
                    height: 56.h,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(12.r),
                      gradient: LinearGradient(
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                        stops: [0.236, 1.0], // 53.6% and 100%
                        colors: [
                          Color(0xFF8A38F5), // Transparent
                          Color(0xFFE20BBB), // Solid #F8F8F8
                        ],
                      ),
                    ),
                    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.generateAiAnalysis.tr(context: context).toText16(isBold: true, color: Colors.white)
                      ],
                    ),
                  ).paddingSymmetrical(24.h, 24.h).onPress(() async {
                    final dialogService = getIt.get<DialogService>();
                    final appState = getIt.get<AppState>();
                    await dialogService.showCommonBottomSheetWithoutH(
                        message: LocaleKeys.aiDisclaimer.tr(),
                        label: LocaleKeys.consent.tr(),
                        okLabel: LocaleKeys.acceptLbl.tr(),
                        cancelLabel: LocaleKeys.rejectView.tr(),
                        onOkPressed: () {
                          context.pop();
                          labViewModel.getAiOverviewLabOrders(langId: appState.getLanguageID(), labOrder: labOrder, loadingText: LocaleKeys.loadingAIAnalysis.tr(context: context));
                        },
                        onCancelPressed: () {
                          context.pop();
                        });
                  }),
                )
              : SizedBox.shrink(),
        ],
      ),
    );
  }
}
