import 'package:easy_localization/easy_localization.dart';
import 'package:fl_chart/fl_chart.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/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/lab/lab_view_model.dart';
import 'package:hmg_patient_app_new/features/lab/models/resp_models/lab_result.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/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/ai_analysis_widget.dart';
import 'package:hmg_patient_app_new/services/dialog_service.dart';
import 'package:hmg_patient_app_new/widgets/date_range_selector/date_range_calender.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_results/lab_result_list_item.dart';
import 'package:hmg_patient_app_new/theme/colors.dart' show AppColors;
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/widgets/date_range_selector/viewmodel/date_range_view_model.dart';
import 'package:hmg_patient_app_new/widgets/graph/custom_graph.dart';
import 'package:provider/provider.dart' show Consumer, Provider, ReadContext, Selector;

import '../../../core/common_models/data_points.dart';
import '../../../widgets/common_bottom_sheet.dart' show showCommonBottomSheetWithoutHeight;
import 'dart:ui' as ui;

class LabResultDetails extends StatefulWidget {
  final LabResult recentLabResult;
  final String? testDescription;

  const LabResultDetails({super.key, required this.recentLabResult, required this.testDescription});

  @override
  State<LabResultDetails> createState() => _LabResultDetailsState();
}

class _LabResultDetailsState extends State<LabResultDetails> {
  final GlobalKey _aiAnalysisKey = GlobalKey();
  LabOrderResponseByAi? _previousAiData;

  LabResult get recentLabResult => widget.recentLabResult;

  String? get testDescription => widget.testDescription;

  @override
  Widget build(BuildContext context) {
    LabViewModel labViewModel = Provider.of<LabViewModel>(context, listen: false);
    final appState = getIt.get<AppState>();
    return Scaffold(
      body: Consumer<LabViewModel>(builder: (context, labVM, child) {
        // Detect changes in labOrderResponseByAi
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (labVM.labOrderResponseByAi != null && _previousAiData == null) {
            // AI data just became available — scroll to it
            final ctx = _aiAnalysisKey.currentContext;
            if (ctx != null) {
              Scrollable.ensureVisible(
                ctx,
                duration: const Duration(milliseconds: 400),
                curve: Curves.easeOut,
              );
            }
          } else if (labVM.labOrderResponseByAi == null && _previousAiData != null) {
            // AI data just became null — scroll to top
            final scrollable = Scrollable.maybeOf(context);
            scrollable?.position.animateTo(
              0,
              duration: const Duration(milliseconds: 400),
              curve: Curves.easeOut,
            );
          }
          _previousAiData = labVM.labOrderResponseByAi;
        });

        return Column(
          children: [
            Expanded(
              child: CollapsingListView(
                title: LocaleKeys.labResultDetails.tr(context: context),
                // 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.getAiOverviewSingleLabResult(langId: appState.getLanguageID().toString(), recentLabResult: recentLabResult, loadingText: LocaleKeys.loadingAIAnalysis.tr(context: context));
                //       },
                //       onCancelPressed: () {
                //         context.pop();
                //       });
                // },
                child: SingleChildScrollView(
                  child: Column(
                    spacing: 16.h,
                    children: [
                      LabNameAndStatus(context),
                      getLabDescription(context),
                      Selector<LabViewModel, List<LabResult>?>(
                        selector: (_, model) => model.mainLabResults,
                        builder: (_, data, __) => Visibility(
                          visible: data?.isNotEmpty == true,
                          child: Column(
                            spacing: 16.h,
                            children: [
                              LabGraph(context),
                              Container(
                                padding: EdgeInsets.symmetric(horizontal: 24.h, vertical: 16.h),
                                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                  color: AppColors.whiteColor,
                                  borderRadius: 24.h,
                                  hasShadow: true,
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        LocaleKeys.history.tr(context: context).toText16(isBold: true, color: AppColors.textColor),
                                        (labVM.isLabResultsHistoryShowMore ? "Show Less" : "Show More")
                                            .toText14(isBold: true, color: AppColors.primaryRedColor, isUnderLine: true)
                                            .onPress(() {
                                          labVM.setIsLabResultsHistoryShowMore();
                                        }),
                                      ],
                                    ),
                                    SizedBox(
                                      height: 24.h,
                                    ),
                                    labHistoryList(labVM),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Selector<LabViewModel, LabOrderResponseByAi?>(
                        selector: (_, model) => model.labOrderResponseByAi,
                        builder: (_, aiData, __) {
                          if (aiData != null) {
                            return AiAnalysisWidget(key: _aiAnalysisKey, data: aiData).paddingOnly(bottom: 16.h);
                          }
                          return const SizedBox.shrink();
                        },
                      ),
                    ],
                  ).paddingAll(24.h),
                ),
              ),
            ),
            Utils.havePrivilege(115) ? labVM.labOrderResponseByAi == null ? 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.generateAiAnalysisResult.tr(context: context).toText16(isBold: true, color: Colors.white)
                  ],
                ),
              ).paddingSymmetrical(24.h, 24.h).onPress(() 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.getAiOverviewSingleLabResult(
                          langId: appState.getLanguageID(), recentLabResult: recentLabResult, loadingText: LocaleKeys.loadingAIAnalysis.tr(context: context));
                    },
                    onCancelPressed: () {
                      context.pop();
                    });
              }),
            ) : SizedBox.shrink() : SizedBox.shrink(),
          ],
        );
      }),
    );
  }

  Widget LabNameAndStatus(BuildContext context) => Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true),
      padding: EdgeInsets.all(16.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        spacing: 8.h,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  (recentLabResult.testCode ?? "").toText28(isBold: true, color: AppColors.textColor, letterSpacing: -2, isEnglishOnly: true),
                  Visibility(
                    visible: recentLabResult.checkIfGraphShouldBeDisplayed() == true,
                    child: Column(
                      spacing: 6.h,
                      children: [
                        context
                            .read<LabViewModel>()
                            .getSeverityText(
                              recentLabResult.calculatedResultFlag ?? "",
                            )
                            .tr(context: context)
                            .toText10(isBold: true, color: AppColors.greyTextColor),
                        Utils.buildSvgWithAssets(
                            icon: AppAssets.lab_result_indicator,
                            width: 21,
                            height: 23,
                            iconColor: context.read<LabViewModel>().getColor(
                                  recentLabResult.calculatedResultFlag ?? "",
                                )),
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 4.h),
              ("${LocaleKeys.resultOf.tr(context: context)} ${recentLabResult.verifiedOn ?? ""}").toText11(isBold: true, color: AppColors.greyTextColor, isEnglishOnly: true),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                child: Row(
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Flexible(
                      child: Directionality(
                        textDirection: ui.TextDirection.ltr,
                        child: ("${recentLabResult.resultValue} ${recentLabResult.uOM}" ?? "").toText28(
                            isBold: true,
                            color: context.read<LabViewModel>().getColor(
                                  recentLabResult.calculatedResultFlag ?? "",
                                ),
                            letterSpacing: -2,
                            isEnglishOnly: true),
                      ),
                    ),
                    SizedBox(
                      width: 4.h,
                    ),
                  ],
                ),
              ),
            ],
          ),
          Visibility(
            visible: recentLabResult.referanceRange != null,
            child: Text(
              "${LocaleKeys.referenceRange.tr(context: context)}: \n${recentLabResult.referanceRange!.trim()}",
              style: TextStyle(
                fontSize: 12.f,
                fontWeight: FontWeight.w600,
                fontFamily: getIt.get<AppState>().isArabic() ? 'CairoArabic' : 'Poppins',
                color: AppColors.greyTextColor,
              ),
              softWrap: true,
            ),
          ),
        ],
      ));

  Widget LabGraph(BuildContext context) => Consumer<LabViewModel>(
        builder: (_, labmodel, ___) => Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 24.h,
              hasShadow: true,
            ),
            height: labmodel.isGraphVisible
                ? 260.h
                : (labmodel.filteredGraphValues.length < 3)
                    ? (labmodel.filteredGraphValues.length * 64) + 80.h
                    : 260.h,
            padding: EdgeInsets.all(14.h),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                //title and filter icon
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    (labmodel.isGraphVisible ? LocaleKeys.historyFlowchart.tr(context: context) : LocaleKeys.history.tr(context: context)).toText16(isBold: true, color: AppColors.textColor),
                    // Text(
                    //   labmodel.isGraphVisible ? LocaleKeys.historyFlowchart.tr(context: context) : LocaleKeys.history.tr(context: context),
                    //   style: TextStyle(
                    //     fontSize: 16.f,
                    //     fontFamily: 'Poppins',
                    //     isBold: true,
                    //     color: AppColors.textColor,
                    //   ),
                    // ),
                    Row(
                      spacing: 16.h,
                      children: [
                        //todo handle when the graph icon is being displayed
                        // Utils.buildSvgWithAssets(icon: labmodel.isGraphVisible ? AppAssets.ic_list : AppAssets.ic_graph, width: 24.h, height: 24.h).onPress(() {
                        //   if (labmodel.shouldShowGraph) {
                        //     labmodel.alterGraphVisibility();
                        //   }
                        // }),
                        Utils.buildSvgWithAssets(icon: AppAssets.ic_date_filter, width: 24, height: 24).onPress(() {
                          showCommonBottomSheetWithoutHeight(
                            title: LocaleKeys.setTheDateRange.tr(context: context),
                            context,
                            child: DateRangeSelector(
                              onRangeSelected: (start, end) {
                                // if (start != null) {
                                labmodel.getSelectedDateRange(start, end);
                                // }
                              },
                            ),
                            isFullScreen: false,
                            isCloseButtonVisible: true,
                            callBackFunc: () {},
                          );
                        }),
                      ],
                    )
                  ],
                ).paddingOnly(bottom: labmodel.isGraphVisible ? 16.h : 24.h),
                historyBody(labmodel)
              ],
            )),
      );

  Widget leftLabels(String value) {
    return Text(
      value,
      style: TextStyle(
        fontWeight: FontWeight.w600,
        fontFamily: getIt.get<AppState>().isArabic() ? 'CairoArabic' : 'Poppins',
        fontSize: 8.f,
        color: AppColors.textColor,
      ),
    );
  }

  Widget buildBottomLabel(String label) {
    return Padding(
      padding: const EdgeInsets.only(top: 8.0),
      child: Text(
        label,
        style: TextStyle(fontSize: 8.f, fontFamily: getIt.get<AppState>().isArabic() ? 'CairoArabic' : 'Poppins', fontWeight: FontWeight.w600, color: AppColors.labelTextColor),
      ),
    );
  }

  Widget historyBody(LabViewModel labmodel) {
    if (labmodel.shouldShowGraph) {
      var graphColor = labmodel.getColor(recentLabResult.calculatedResultFlag ?? "N");
      return CustomGraph(
          dataPoints: labmodel.filteredGraphValues,
          makeGraphBasedOnActualValue: true,
          leftLabelReservedSize: 40,
          showGridLines: true,
          leftLabelInterval: getInterval(labmodel),
          // maxY: (labmodel.maxY)+(getInterval(labmodel)??0)/2,
          maxY: (labmodel.maxY),
          minY: labmodel.minY,
          maxX: labmodel.filteredGraphValues.length.toDouble() - .75,
          horizontalInterval: .01,
          isRTL: getIt.get<AppState>().isArabic(),
          getDrawingHorizontalLine: (value) {
            value = double.parse(value.toStringAsFixed(2));
            // print("the value is $value");
            if (value == labmodel.highRefrenceValue || value == labmodel.lowRefenceValue) {
              return FlLine(
                color: AppColors.bgGreenColor.withOpacity(0.6),
                strokeWidth: 1,
                // dashArray: [5, 5],
              );
            }
            return FlLine(
              color: Colors.transparent,
              strokeWidth: 1,
            );
            ;
          },
          leftLabelFormatter: (value) {
            value = double.parse(value.toStringAsFixed(2));
            return leftLabels(value.toStringAsFixed(2));
            // if (value == labmodel.highRefrenceValue) {
            //   return leftLabels(LocaleKeys.high.tr());
            // }
            //
            // if (value == labmodel.lowRefenceValue) {
            //   return leftLabels(LocaleKeys.low.tr());
            // }

            return SizedBox.shrink();
            // }
          },
          graphColor: AppColors.textColor.withAlpha(90),
          graphShadowColor: AppColors.graphGridColor.withOpacity(.5),
          graphGridColor: graphColor.withOpacity(.4),
          bottomLabelFormatter: (value, data) {
            if (data.isEmpty) return SizedBox.shrink();
            if (value == 0) {
              return buildBottomLabel(data[value.toInt()].label);
            }
            if (value == data.length - 1) {
              return buildBottomLabel(data[value.toInt()].label);
            }
            if (value == ((data.length - 1) / 2)) {
              return buildBottomLabel(data[value.toInt()].label);
            }
            return SizedBox.shrink();
          },
          rangeAnnotations: RangeAnnotations(horizontalRangeAnnotations: _buildRangeShades(labmodel)),
          minX: (labmodel.filteredGraphValues.length == 1) ? null : -.2,
          scrollDirection: Axis.horizontal,
          height: 180.h);
    }
    return SizedBox.shrink();
  }

  List<HorizontalRangeAnnotation> _buildRangeShades(
    LabViewModel model,
  ) {
    List<HorizontalRangeAnnotation> ranges = [];

    ranges.add(HorizontalRangeAnnotation(
      y1: model.minY,
      y2: model.lowRefenceValue,
      color: Colors.transparent,
    ));

    ranges.add(HorizontalRangeAnnotation(
      y1: model.lowRefenceValue,
      y2: model.highRefrenceValue,
      color: AppColors.bgGreenColor.withOpacity(0.05),
    ));

    ranges.add(HorizontalRangeAnnotation(
      y1: model.highRefrenceValue,
      y2: model.maxY,
      color: Colors.transparent,
    ));
    return ranges;
  }

  Widget labHistoryList(LabViewModel labmodel) {
    return SizedBox(
      height: labmodel.mainLabResults.length < 3 ? labmodel.mainLabResults.length * 64 : (!labmodel.isLabResultsHistoryShowMore ? 180.h : 220.h),
      child: ListView.separated(
        padding: EdgeInsets.zero,
        // itemCount: labmodel.isLabResultsHistoryShowMore ? (labmodel.filteredGraphValues.length < 3 ? labmodel.filteredGraphValues : 3) : labmodel.filteredGraphValues.length,
        itemCount: !labmodel.isLabResultsHistoryShowMore ? (labmodel.mainLabResults.length < 3 ? labmodel.mainLabResults.length : 3) : labmodel.mainLabResults.length,
        itemBuilder: (context, index) {
          var data = labmodel.mainLabResults.toList()[index];
          return LabHistoryItem(
            dayNameAndDate: labmodel.getFormattedDate(DateUtil.convertStringToDate(data.verifiedOnDateTime)),
            result: data.resultValue??"",
            assetUrl: labmodel.getAssetUrlWRTResult(data.calculatedResultFlag??""),
            shouldRotateIcon: labmodel.getRotationWRTResult(data.calculatedResultFlag??""),
          );
        },
        separatorBuilder: (_, __) => Divider(
          color: AppColors.spacerLineColor,
          thickness: 1.h,
        ).paddingOnly(top: 4.h, bottom: 4.h),
      ),
    );
  }

  double? getInterval(LabViewModel labmodel) {
    // return .1;
    var maxX = labmodel.maxY;
    if(maxX<1) return .3;
    if(maxX >1 && maxX <= 5) return .7;
    if(maxX >5 && maxX <= 10) return 2.5;
    if(maxX >10 && maxX <= 50) return 5;
    if(maxX >50 && maxX <= 100) return 10;
    if(maxX >100 && maxX <= 200) return 30;
    if(maxX >200 && maxX <= 300) return 50;
    if(maxX >300 && maxX <= 400) return 100;
    return 200 ;
  }

  Widget getLabDescription(BuildContext context) {
    return Container(
      width: MediaQuery.sizeOf(context).width,
        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
          color: AppColors.whiteColor,
          borderRadius: 24.h,
          hasShadow: true,
        ),
        padding: EdgeInsets.all(16.h),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          spacing: 8.h,
          children: [
            LocaleKeys.whatIsThisResult.tr(context: context).toText16(isBold: true, color: AppColors.textColor),
            testDescription?.toText12(isBold: true, color: AppColors.textColorLight) ?? SizedBox.shrink()
          ],
        ));
  }
}
