import 'dart:async';

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_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/radiology/models/resp_models/patient_radiology_response_model.dart';
import 'package:hmg_patient_app_new/features/radiology/radiology_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/services/dialog_service.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_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/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';
import 'package:url_launcher/url_launcher.dart';
import 'dart:ui' as ui;

class RadiologyResultPage extends StatefulWidget {
  const RadiologyResultPage({super.key, required this.patientRadiologyResponseModel});

  final PatientRadiologyResponseModel patientRadiologyResponseModel;

  @override
  State<RadiologyResultPage> createState() => _RadiologyResultPageState();
}

class _RadiologyResultPageState extends State<RadiologyResultPage> {
  late RadiologyViewModel radiologyViewModel;

  @override
  void initState() {
    scheduleMicrotask(() {
      radiologyViewModel.getRadiologyImage(patientRadiologyResponseModel: widget.patientRadiologyResponseModel);
    });
    super.initState();
  }

  @override
  void dispose() {
    // Clear AI analysis data when leaving the screen
    radiologyViewModel.closeRadiologyAIAnalysis();
    // radiologyViewModel.setIsRadiologyAIAnalysisNeedsToBeShown(true);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    radiologyViewModel = Provider.of<RadiologyViewModel>(context, listen: false);
    AppState _appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Consumer<RadiologyViewModel>(builder: (context, radVM, child) {

        return Column(
          children: [
            Expanded(
              child: CollapsingListView(
                title: LocaleKeys.radiologyResult.tr(context: context),
                downloadReport: () async {
                  LoaderBottomSheet.showLoader();
                  await radiologyViewModel
                      .getRadiologyPDF(
                          patientRadiologyResponseModel: widget.patientRadiologyResponseModel,
                          authenticatedUser: _appState.getAuthenticatedUser()!,
                          onError: (err) {
                            LoaderBottomSheet.hideLoader();
                            showCommonBottomSheetWithoutHeight(
                              context,
                              child: Utils.getErrorWidget(loadingText: err),
                              callBackFunc: () {},
                              isFullScreen: false,
                              isCloseButtonVisible: true,
                            );
                          })
                      .then((val) async {
                    LoaderBottomSheet.hideLoader();
                    if (radiologyViewModel.patientRadiologyReportPDFBase64.isNotEmpty) {
                      String path = await Utils.createFileFromString(radiologyViewModel.patientRadiologyReportPDFBase64, "pdf");
                      try {
                        OpenFilex.open(path);
                      } catch (ex) {
                        showCommonBottomSheetWithoutHeight(
                          context,
                          child: Utils.getErrorWidget(loadingText: "Cannot open file"),
                          callBackFunc: () {},
                          isFullScreen: false,
                          isCloseButtonVisible: true,
                        );
                      }
                    }
                  });
                },
                // viewImage: () {
                //   if (radiologyViewModel.radiologyImageURL.isNotEmpty) {
                //     Uri uri = Uri.parse(radiologyViewModel.radiologyImageURL);
                //     launchUrl(uri, mode: LaunchMode.platformDefault, webOnlyWindowName: "");
                //   } else {
                //     Utils.showToast("Radiology image not available");
                //   }
                // },
                child: SingleChildScrollView(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 24.h),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(height: 24.h),
                        Container(
                          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                            color: AppColors.whiteColor,
                            borderRadius: 20.h,
                            hasShadow: true,
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              SizedBox(height: 16.h),
                              // widget.patientRadiologyResponseModel.description!.toText16(isBold: true),
                              SizedBox(height: 8.h),
                              Directionality(
                                textDirection: ui.TextDirection.ltr,
                                child: widget.patientRadiologyResponseModel.reportData!.trim().toText12(isBold: true, color: AppColors.textColorLight, isEnglishOnly: true),
                              ),
                              SizedBox(height: 16.h),
                              // CustomButton(
                              //   text: LocaleKeys.viewRadiologyImage.tr(context: context),
                              //   onPressed: () async {
                              //     if (radiologyViewModel.radiologyImageURL.isNotEmpty) {
                              //       Uri uri = Uri.parse(radiologyViewModel.radiologyImageURL);
                              //       launchUrl(uri, mode: LaunchMode.platformDefault, webOnlyWindowName: "");
                              //     } else {
                              //       Utils.showToast("Radiology image not available");
                              //     }
                              //   },
                              //   backgroundColor: AppColors.primaryRedColor,
                              //   borderColor: AppColors.primaryRedColor,
                              //   textColor: Colors.white,
                              //   fontSize: 14,
                              //   isBold: true,
                              //   borderRadius: 12,
                              //   padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                              //   height: 40.h,
                              //   icon: AppAssets.download,
                              //   iconColor: Colors.white,
                              //   iconSize: 20.h,
                              // ),
                              // SizedBox(height: 16.h),
                            ],
                          ).paddingSymmetrical(16.h, 0.h),
                        ),
                        SizedBox(height: 24.h),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            Container(
                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                      color: AppColors.whiteColor,
                      borderRadius: 24.h,
                      hasShadow: true,
                    ),
                    child: Column(
                      children: [
                        SizedBox(height: 24.h),
                        widget.patientRadiologyResponseModel.dIAPACSURL != ""
                            ? CustomButton(
                                text: LocaleKeys.openRad.tr(context: context),
                                onPressed: () async {
                                  if (radiologyViewModel.radiologyImageURL.isNotEmpty) {
                                    Uri uri = Uri.parse(radiologyViewModel.radiologyImageURL);
                                    launchUrl(uri, mode: LaunchMode.platformDefault, webOnlyWindowName: "");
                                  } else {
                                    Utils.showToast("Radiology image not available");
                                  }
                                },
                                backgroundColor: AppColors.primaryRedColor,
                                borderColor: AppColors.primaryRedColor,
                                textColor: Colors.white,
                                fontSize: 16,
                                isBold: true,
                                borderRadius: 12,
                                padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                height: 56.h,
                                icon: AppAssets.imageIcon,
                                iconColor: Colors.white,
                                iconSize: 20.h,
                              ).paddingSymmetrical(24.h, 0.h)
                            : SizedBox.shrink(),
                        Utils.havePrivilege(116) ? 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.generateAiAnalysisRadResult.tr(context: context).toText16(isBold: true, color: Colors.white)
                            ],
                          ),
                        ).paddingSymmetrical(24.h, 12.h).onPress(() async {
                          final _dialogService = getIt.get<DialogService>();
                          await _dialogService.showCommonBottomSheetWithoutH(
                          message: LocaleKeys.aiDisclaimerRad.tr(),
                            label: LocaleKeys.consent.tr(),
                            okLabel: LocaleKeys.acceptLbl.tr(),
                            cancelLabel: LocaleKeys.rejectView.tr(),
                            onOkPressed: () {
                              context.pop();
                              radiologyViewModel.getRadiologyAiAnalysis(
                                reportData: widget.patientRadiologyResponseModel.reportData ?? "",
                                loadingText: LocaleKeys.loadingAIAnalysis.tr(context: context),
                                langId: _appState.getLanguageID(),
                              );
                            },
                            onCancelPressed: () {
                              context.pop();
                            },
                          );
                        })  : SizedBox(height: 24.h),
                      ],
                    ),
                  ),
          ],
        );
      }),
    );
  }
}
