import 'dart:convert';

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/generated/locale_keys.g.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/expandable_list_widget.dart';
import 'package:provider/provider.dart';

import '../../../features/lab/models/resp_models/ai_overview_labresults_by_ai_model.dart';

class LabAiAnalysisDetailedPage extends StatefulWidget {
  const LabAiAnalysisDetailedPage({super.key});

  @override
  State<LabAiAnalysisDetailedPage> createState() => _LabAiAnalysisDetailedPageState();
}

class _LabAiAnalysisDetailedPageState extends State<LabAiAnalysisDetailedPage> {
  late LabViewModel labProvider;

  @override
  Widget build(BuildContext context) {
    labProvider = Provider.of<LabViewModel>(context, listen: false);
    return CollapsingListView(
      isClose: true,
      title: LocaleKeys.aiAnalysis.tr(context: context),
      child: Consumer<LabViewModel>(
        builder: (context, model, child) {
          if (model.labOrdersResponseByAi == null || model.labOrdersResponseByAi?.analysis == null) {
            return Utils.getNoDataWidget(context);
          }

          final analysis = model.labOrdersResponseByAi!.analysis!;
          List<ExpandableListItem> expandableItems = [];

          // Summary Section
          if (analysis.summary != null && analysis.summary!.isNotEmpty) {
            expandableItems.add(
              ExpandableListItem(
                backgroundColor: Colors.transparent,
                expandedBackgroundColor:Colors.transparent ,
                title: LocaleKeys.summary.tr(context: context).toText18(weight: FontWeight.w700, color: AppColors.blackColor),
                initiallyExpanded: true,
                children: [
                  SizedBox(height: 10.h),
                  Container(

                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 12.r, side: BorderSide(width: 1, color: Color(0xFF0B85F7))),
                    padding: EdgeInsets.all(16.r),
                    child: (analysis.summary ?? "").toText14(color: AppColors.textColorLight, height: 1.5, weight: FontWeight.w400),
                  ),
                  SizedBox(height: 8.h),
                ],
              ),
            );
          }

          // AI Generated Attributes Section (Lab Test Results)
          if (analysis.aiGeneratedAttributes != null && analysis.aiGeneratedAttributes!.isNotEmpty) {
            expandableItems.add(
              ExpandableListItem(

                backgroundColor: Colors.transparent,
                expandedBackgroundColor:Colors.transparent ,
                title: LocaleKeys.labResults.tr(context: context).toText18(weight: FontWeight.w700, color: AppColors.blackColor),
                children: [
                  SizedBox(height: 10.h),
                  ...analysis.aiGeneratedAttributes!.map((attr) {
                    return Column(
                      children: [
                        _buildCombinedLabCard(attr),
                        SizedBox(height: 16.h),
                      ],
                    );
                  }).toList(),
                ],
              ),
            );
          }

          // AI Predictions Section
          if (analysis.aiPredictions != null && analysis.aiPredictions!.isNotEmpty) {
            expandableItems.add(
              ExpandableListItem(
                backgroundColor: Colors.transparent,
                expandedBackgroundColor:Colors.transparent ,
                title: LocaleKeys.prediction.tr(context: context).toText18(weight: FontWeight.w700, color: AppColors.blackColor),
                children: [
                  SizedBox(height: 10.h),
                  Container(
                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 12.r, side: BorderSide(width: 1, color: Color(0xFFFFAF15))),
                    padding: EdgeInsets.all(16.r),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: analysis.aiPredictions!.map((prediction) => _buildBulletItem(prediction)).toList(),
                    ),
                  ),
                  SizedBox(height: 8.h),
                ],
              ),
            );
          }

          // AI Recommendations Section
          if (analysis.aiRecommendations != null && analysis.aiRecommendations!.isNotEmpty) {
            expandableItems.add(
              ExpandableListItem(
                backgroundColor: Colors.transparent,
                expandedBackgroundColor:Colors.transparent ,
                title: LocaleKeys.suggestions.tr(context: context).toText18(weight: FontWeight.w700, color: AppColors.blackColor),
                children: [
                  SizedBox(height: 10.h),
                  Container(
                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 12.r),
                    padding: EdgeInsets.all(16.r),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: analysis.aiRecommendations!.asMap().entries.map((entry) {
                        final rec = entry.value;
                        final isLast = entry.key == analysis.aiRecommendations!.length - 1;
                        return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            if (rec.priority != null) ...[
                              Container(
                                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                                decoration: BoxDecoration(color: _getPriorityColor(rec.priority), borderRadius: BorderRadius.circular(4.r)),
                                child: rec.priority!.toText12(isBold: true, color: _getPriorityTextColor(rec.priority)),
                              ),
                              SizedBox(height: 8.h),
                            ],
                            (rec.recommendation ?? "").toText14(
                              color: AppColors.textColorLight,
                              height: 1.5,
                              weight: FontWeight.w400,
                            ),
                            if (!isLast) ...[
                              SizedBox(height: 12.h),
                              Divider(color: AppColors.dividerColor, thickness: 1),
                              SizedBox(height: 12.h),
                            ],
                          ],
                        );
                      }).toList(),
                    ),
                  ),
                  SizedBox(height: 8.h),
                ],
              ),
            );
          }

          // Risk Factors Section
          if (analysis.riskFactors != null && analysis.riskFactors!.isNotEmpty) {
            expandableItems.add(
              ExpandableListItem(
                backgroundColor: Colors.transparent,
                expandedBackgroundColor:Colors.transparent ,
                title: LocaleKeys.riskFactors.tr(context: context).toText18(weight: FontWeight.w700, color: AppColors.blackColor),
                children: [
                  SizedBox(height: 10.h),
                  ...analysis.riskFactors!.asMap().entries.map((entry) {
                    final risk = entry.value;
                    return Column(
                      children: [
                        Container(
                          decoration: RoundedRectangleBorder()
                              .toSmoothCornerDecoration(color: Color(0xFFFBCB6E).withOpacity(0.10), borderRadius: 12.r, side: BorderSide(width: 1, color: Color(0xFFFBCB6E).withOpacity(0.10))),
                          padding: EdgeInsets.all(16.r),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Expanded(
                                    child: Container(
                                      decoration: BoxDecoration(color: Color(0xFFFBCB6E).withAlpha(38), borderRadius: BorderRadius.circular(8)),
                                      child: Padding(
                                        padding: const EdgeInsets.all(8.0),
                                        child: (risk.risk ?? "").toText10(isBold: true, color: AppColors.blackColor),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              if (risk.risk != null && risk.risk!.isNotEmpty) ...[
                                SizedBox(height: 4.h),
                                Row(
                                  children: [
                                    Utils.buildSvgWithAssets(icon: AppAssets.guradIcon),
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: (risk.factor ?? "").toText16(weight: FontWeight.w700, color: AppColors.blackColor),
                                    ),
                                  ],
                                ),
                                SizedBox(height: 4.h),
                                (risk.description ?? "").toText14(
                                  color: AppColors.textColorLight,
                                  height: 1.5,
                                  weight: FontWeight.w400,
                                ),
                              ],
                              if (risk.description != null && risk.description!.isNotEmpty) ...[
                                SizedBox(height: 8.h),
                                (risk.description ?? "").toText14(
                                  color: AppColors.textColorLight,
                                  height: 1.5,
                                  weight: FontWeight.w400,
                                ),
                              ],
                            ],
                          ),
                        ),
                        SizedBox(height: 16.h),
                      ],
                    );
                  }).toList(),
                ],
              ),
            );
          }

          // Prevention Section
          if (analysis.prevention != null && analysis.prevention!.isNotEmpty) {
            expandableItems.add(
              ExpandableListItem(
                backgroundColor: Colors.transparent,
                expandedBackgroundColor:Colors.transparent ,
                title: LocaleKeys.prevention.tr(context: context).toText18(weight: FontWeight.w700, color: AppColors.blackColor),
                children: [
                  SizedBox(height: 10.h),
                  Container(
                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 12.r, side: BorderSide(width: 1, color: Color(0xFF18C273))),
                    padding: EdgeInsets.all(16.r),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: analysis.prevention!.map((prevention) => _buildBulletItem(prevention)).toList(),
                    ),
                  ),
                  SizedBox(height: 8.h),
                ],
              ),
            );
          }

          // // Suggested Doctors Section
          // if (analysis.suggestedDoctors != null && analysis.suggestedDoctors!.isNotEmpty) {
          //   expandableItems.add(
          //     ExpandableListItem(
          //       title: "Suggested Doctors".toText18(weight: FontWeight.w700, color: AppColors.blackColor),
          //       children: [
          //         SizedBox(height: 10.h),
          //         Container(
          //           decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
          //             color: AppColors.whiteColor,
          //             borderRadius: 12.r,
          //             side: BorderSide(width: 1, color: Color(0xFF3498DB)),
          //           ),
          //           padding: EdgeInsets.all(16.r),
          //           child: Column(
          //             crossAxisAlignment: CrossAxisAlignment.start,
          //             children: analysis.suggestedDoctors!.asMap().entries.map((entry) {
          //               final doctor = entry.value;
          //               final isLast = entry.key == analysis.suggestedDoctors!.length - 1;
          //               return Column(
          //                 crossAxisAlignment: CrossAxisAlignment.start,
          //                 children: [
          //                   Row(
          //                     children: [
          //                       Container(
          //                         width: 40.r,
          //                         height: 40.r,
          //                         decoration: BoxDecoration(
          //                           gradient: AppColors.aiLinearGradient,
          //                           shape: BoxShape.circle,
          //                         ),
          //                         child: Icon(
          //                           Icons.person,
          //                           color: Colors.white,
          //                           size: 24.r,
          //                         ),
          //                       ),
          //                       SizedBox(width: 12.w),
          //                       Expanded(
          //                         child: doctor.toString().toText14(
          //                               color: AppColors.textColorLight,
          //                               height: 1.5,
          //                               weight: FontWeight.w600,
          //                             ),
          //                       ),
          //                     ],
          //                   ),
          //                   if (!isLast) ...[
          //                     SizedBox(height: 12.h),
          //                     const Divider(color: AppColors.dividerColor, thickness: 1),
          //                     SizedBox(height: 12.h),
          //                   ],
          //                 ],
          //               );
          //             }).toList(),
          //           ),
          //         ),
          //         SizedBox(height: 8.h),
          //       ],
          //     ),
          //   );
          // }

          return Column(
            children: [
              if (expandableItems.isEmpty)
                Utils.getNoDataWidget(context)
              else
                CustomExpandableList(
                  expansionMode: ExpansionMode.exactlyOne,
                  dividerColor: AppColors.dividerColor,
                  itemPadding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 14.h),
                  items: expandableItems,
                  theme: ExpandableListTheme.custom(

                    defaultTrailingIcon: Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, height: 22.h, width: 22.w, iconColor: AppColors.textColor),
                  ),
                ).paddingSymmetrical(16.w, 0.0),
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Icon(Icons.info_outline, color: AppColors.greyTextColor, size: 20.r),
                  SizedBox(width: 8.w),
                  Expanded(
                    child: ("${LocaleKeys.disclaimer.tr()}:${LocaleKeys.thisAboveInfo.tr()}").toText12(color: AppColors.greyTextColor, fontWeight: FontWeight.w400),
                  ),
                ],
              ).paddingSymmetrical(16.w, 16.h)
            ],
          );
        },
      ),
    );
  }

  Color _getPriorityColor(String? priority) {
    if (priority == null) return AppColors.primaryRedColor;
    switch (priority.toLowerCase()) {
      case 'high':
        return AppColors.secondaryLightRedColor;
      case 'medium' || 'moderate':
        return AppColors.lightGreenButtonColor;
      case 'low':
        return AppColors.warningColorYellow.withOpacity(.3);
      default:
        return AppColors.primaryRedColor;
    }
  }

  Color _getPriorityTextColor(String? priority) {
    if (priority == null) return AppColors.whiteColor;
    switch (priority.toLowerCase()) {
      case 'high':
        return AppColors.primaryRedColor;
      case 'medium' || 'moderate':
        return AppColors.textGreenColor;
      case 'low':
        return AppColors.alertColor;
      default:
        return AppColors.primaryRedColor;
    }
  }



  Color _getResultFlagColor(String? flag) {
    if (flag == null || flag.isEmpty) return Colors.grey;
    switch (flag.toUpperCase()) {
      case 'H': // High
      case 'HH': // Very High
      case 'CRITICAL HIGH':
        return AppColors.lightRedButtonColor;
      case 'L': // Low
      case 'LL': // Very Low
      case 'CRITICAL LOW':
        return AppColors.chipColorSeekMedicalAdvice.withAlpha(75);
      case 'N': // Normal
        return AppColors.lightGreenButtonColor;
      case 'A': // Abnormal
        return Colors.deepOrange;
      default:
        return AppColors.greyLightColor;
    }
  }

  Color _getResultTextColor(String? priority) {
    if (priority == null) return AppColors.whiteColor;
    switch (priority.toUpperCase()) {
      case 'H': // High
      case 'HH': // Very High
      case 'CRITICAL HIGH':
        return AppColors.primaryRedColor;
      case 'N':
        return AppColors.textGreenColor;
      case 'L': // Low
      case 'LL': // Very Low
      case 'CRITICAL LOW':
        return AppColors.chipTextColorSeekMedicalAdvice;
      default:
        return AppColors.textColor;
    }
  }

  Widget _buildBulletItem(String text) {
    return Padding(
      padding: EdgeInsets.only(bottom: 12.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: text.toText14(color: AppColors.textColorLight, height: 1.5, weight: FontWeight.w400),
          ),
        ],
      ),
    );
  }

  Widget _buildCombinedLabCard(AiGeneratedAttribute attr) {
    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: false),
      padding: EdgeInsets.all(16.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        spacing: 2.h,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (attr.calculatedResultFlag != null && attr.calculatedResultFlag!.isNotEmpty && attr.calculatedResultFlag == "-") ...[
                Row(
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                      decoration: BoxDecoration(color: AppColors.greyLightColor, borderRadius: BorderRadius.circular(4.r)),
                      child: Row(
                        children: [
                          Utils.buildSvgWithAssets(icon: AppAssets.informationIcon, width: 14.w, height: 14.h),
                          SizedBox(width: 4.w),
                          LocaleKeys.contextDependent.tr().toText12(isBold: true, color: AppColors.textColor),
                        ],
                      ),
                    ),
                  ],
                ),
              ] else ...[
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                      decoration: BoxDecoration(color: _getResultFlagColor(attr.calculatedResultFlag), borderRadius: BorderRadius.circular(4.r)),
                      child: Row(
                        children: [
                          (attr.calculatedResultFlag ?? "").toText12(isBold: true, color: _getResultTextColor(attr.calculatedResultFlag)),
                        ],
                      ),
                    ),
                    if (attr.calculatedResultFlag != null && attr.calculatedResultFlag!.isNotEmpty && attr.calculatedResultFlag == "H")
                      Utils.buildSvgWithAssets(icon: AppAssets.highCautionIcon, iconColor: AppColors.primaryRedColor, width: 24.w, height: 24.h),
                  ],
                ),
              ],
              SizedBox(height: 4.h),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(child: (attr.description ?? "").toText16(isBold: true, color: _getResultTextColor(attr.calculatedResultFlag))),

                  //  if (attr.calculatedResultFlag != null && attr.calculatedResultFlag!.isNotEmpty)
                  // Column(
                  //   spacing: 2.h,
                  //   children: [
                  //     Consumer<LabViewModel>(
                  //       builder: (context, labViewModel, child) {
                  //         return labViewModel.getSeverityText(attr.calculatedResultFlag ?? "").tr(context: context).toText10(isBold: true, color: AppColors.greyTextColor);
                  //       },
                  //     ),
                  //     Consumer<LabViewModel>(
                  //       builder: (context, labViewModel, child) {
                  //         return Utils.buildSvgWithAssets(
                  //           icon: AppAssets.lab_result_indicator,
                  //           width: 21,
                  //           height: 23,
                  //           iconColor: labViewModel.getColor(attr.calculatedResultFlag ?? ""),
                  //         );
                  //       },
                  //     ),
                  //   ],
                  // ),
                ],
              ),
              SizedBox(height: 4.h),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(child: (attr.testShortDescription ?? "").toText12(color: AppColors.textColor)),
                ],
              ),
              SizedBox(height: 4.h)
            ],
          ),
          Row(
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                decoration: BoxDecoration(color: _getResultFlagColor(attr.calculatedResultFlag), borderRadius: BorderRadius.circular(4.r)),
                child: ("${LocaleKeys.calculatedValue.tr()}: ${attr.resultValue!}").toText12(
                  isBold: true,
                  color: _getResultTextColor(attr.calculatedResultFlag),
                  isEnglishOnly: true
                ),
              ),
              SizedBox(width: 8.h),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                decoration: BoxDecoration(color: AppColors.greyLightColor, borderRadius: BorderRadius.circular(4.r)),
                child: ("${LocaleKeys.unit.tr()}: ${attr.uom!}").toText12(isBold: true, color: AppColors.textColor),
              ),
            ],
          ),
          SizedBox(
            height: 4.h,
          ),
          if (attr.referanceRange != null && attr.referanceRange!.isNotEmpty)
            Container(
              padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
              decoration: BoxDecoration(color: AppColors.greyLightColor, borderRadius: BorderRadius.circular(4.r)),
              child: ("${LocaleKeys.referenceRange.tr(context: context)}: ${attr.referanceRange!.trim()}").toText12(isBold: true, color: AppColors.textColor),
            ),
          if (attr.calculationFormula != null && attr.calculationFormula!.isNotEmpty) ...[
            SizedBox(height: 8.h),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Utils.buildSvgWithAssets(icon: AppAssets.calendar, iconColor: Colors.grey),
                SizedBox(width: 8.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      LocaleKeys.calculationFormula.tr().toText16(isBold: true),
                      (attr.calculationFormula ?? "").toText12(isBold: true, color: AppColors.textColorLight, isEnglishOnly: true),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ],
      ),
    );
  }
}
