
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/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/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/generated/locale_keys.g.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/graph/custom_graph.dart';
import 'package:provider/provider.dart' show Consumer, Provider, ReadContext;

import '../../../widgets/common_bottom_sheet.dart'
    show showCommonBottomSheetWithoutHeight;

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

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

  @override
  Widget build(BuildContext context) {
    return CollapsingListView(
      title: 'Lab Result Details'.needTranslation,
      child: SingleChildScrollView(
        child: Column(
          spacing: 16.h,
          children: [
            LabNameAndStatus(context),
            getLabDescription(context),
            LabGraph(context)
          ],
        ).paddingAll(24.h),
      ),
    );
  }

  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: [
              Text(
                recentLabResult.testCode ?? "",
                style: TextStyle(
                    fontSize: 32,
                    fontFamily: 'Poppins',
                    fontWeight: FontWeight.w600,
                    color: AppColors.textColor,
                    letterSpacing: -2),
              ),
              Text(
                "Result of ${recentLabResult.verifiedOn ?? ""}".needTranslation,
                style: TextStyle(
                  fontSize: 12,
                  fontFamily: 'Poppins',
                  fontWeight: FontWeight.w500,
                  color: AppColors.greyTextColor,
                ),
              ),
            ],
          ),
          //todo change the text color according to the provided test values
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,

            children: [
              Expanded(
                child: Row(

                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Flexible(
                      child: Text(
                        "${recentLabResult.resultValue} ${recentLabResult.uOM}" ??
                            "",
                        style: TextStyle(
                          fontSize: 24.fSize,
                          fontWeight: FontWeight.w600,
                          fontFamily: 'Poppins',
                          color: context.read<LabViewModel>().getColor(
                                recentLabResult.calculatedResultFlag ?? "",
                          ),
                          letterSpacing: -2,
                        ),
                        overflow: TextOverflow.ellipsis, // prevent overflow
                        maxLines: 1,
                        softWrap: false,
                      ),
                    ),
                    SizedBox(width: 4.h,),
                    Expanded(
                      flex: 2,
                      child: Visibility(
                        visible: recentLabResult.referanceRange != null,
                        child: Text(
                          "(Reference range ${recentLabResult.referanceRange})".needTranslation,
                          style: TextStyle(
                            fontSize: 12.fSize,
                            fontWeight: FontWeight.w500,
                            fontFamily: 'Poppins',
                            color: AppColors.greyTextColor,
                          ),
                          // overflow: TextOverflow.ellipsis,
                          // maxLines: 2,
                          softWrap: true,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Visibility(
                visible:
                    recentLabResult.checkIfGraphShouldBeDisplayed() == true,
                child: Column(
                  spacing: 6.h,
                  children: [
                    context
                        .read<LabViewModel>()
                        .getSeverityText(
                          recentLabResult.calculatedResultFlag ?? "",
                        )
                        .tr()
                        .toText10(
                            weight: FontWeight.w500,
                            color: AppColors.greyTextColor),
                    Utils.buildSvgWithAssets(
                        icon: AppAssets.lab_result_indicator,
                        width: 21,
                        height: 23,
                        iconColor: context.read<LabViewModel>().getColor(
                              recentLabResult.calculatedResultFlag ?? "",
                            )),
                  ],
                ),
              ),
              // SizedBox(
              //   width: 21,
              //   child: Utils.buildSvgWithAssets(
              //     icon: AppAssets.lab_result_indicator,
              //     width: 21,
              //     height: 23,
              //     iconColor: context.read<LabViewModel>().getColor(
              //           recentLabResult.calculatedResultFlag ?? "",
              //     ),
              //   ),
              // ),
            ],
          )

        ],
      ));

  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(16.h),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                //title and filter icon
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      labmodel.isGraphVisible
                          ? LocaleKeys.historyFlowchart.tr()
                          : LocaleKeys.history.tr(),
                      style: TextStyle(
                        fontSize: 16,
                        fontFamily: 'Poppins',
                        fontWeight: FontWeight.w600,
                        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,
                            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: 'Poppins',
        fontSize: 8.fSize,
        color: AppColors.textColor,
      ),
    );
  }

  Widget buildBottomLabel(String label) {
    return Padding(
      padding: const EdgeInsets.only(top:8.0),
      child: Text(
        label,
        style: TextStyle(
            fontSize: 8.fSize,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w600,
            color: AppColors.labelTextColor),
      ),
    );
  }

  Widget historyBody(LabViewModel labmodel) {
    if (labmodel.isGraphVisible && labmodel.shouldShowGraph) {
      var graphColor = labmodel.getColor(recentLabResult.calculatedResultFlag??"N");
      return CustomGraph(
          dataPoints: labmodel.filteredGraphValues,
          makeGraphBasedOnActualValue: true,
          leftLabelReservedSize: 40,
          leftLabelInterval: getInterval(labmodel),
          maxY: (labmodel.maxY)+(getInterval(labmodel)??0)/2,
          maxX: labmodel.filteredGraphValues.length.toDouble()-.75,
          leftLabelFormatter: (value) {
            return leftLabels(value.toStringAsFixed(2));
            // switch (value.toInt()) {
            //   case 10:
            //     return leftLabels("Critical Low".needTranslation);
            //   case 30:
            //     return leftLabels("Low".needTranslation);
            //   case 50:
            //     return leftLabels("Normal".needTranslation);
            //   case 70:
            //     return leftLabels("High".needTranslation);
            //   case 90:
            //     return leftLabels(
            //         "Critical High".needTranslation);
            //   default:
            //     return SizedBox.shrink();
            // }
          },
          graphColor:graphColor ,
          graphShadowColor: graphColor.withOpacity(.1),
          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();
          },
          minX:(labmodel.filteredGraphValues.length == 1)?null : -.2,
          scrollDirection: Axis.horizontal,
          height: 180.h);
    }else {
      return labHistoryList(labmodel);
    }
  }

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

  double? getInterval(LabViewModel labmodel) {
    var maxX = labmodel.maxY;
    if(maxX<1) return .5;
    if(maxX >1 && maxX < 5) return 1;
    if(maxX >5 && maxX < 10) return 5;
    if(maxX >10 && maxX < 50) return 10;
    if(maxX >50 && maxX < 100) return 20;
    if(maxX >100 && maxX < 200) return 30;
    return 50;
  }

  Widget getLabDescription(BuildContext context) {
    return 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: [
            "What is this result?"
                .needTranslation
                .toText16(weight: FontWeight.w600, color: AppColors.textColor),
            testDescription?.toText12(
                    fontWeight: FontWeight.w500, color: AppColors.textColorLight) ??
                SizedBox.shrink()
          ],
        ));
  }
}
