import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:hmg_patient_app_new/core/app_assets.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/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.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/features/lab/lab_view_model.dart';
import 'package:hmg_patient_app_new/presentation/lab/search_lab_report.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/shimmer/movies_shimmer_widget.dart';
import 'package:provider/provider.dart';

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

  @override
  State<LabOrdersPage> createState() => _LabOrdersPageState();
}

class _LabOrdersPageState extends State<LabOrdersPage> {
  late LabViewModel labProvider;
  List<List<TestDetails>?> labSuggestions = [];
  int? expandedIndex;

  @override
  void initState() {
    scheduleMicrotask(() {
      labProvider.initLabProvider();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    labProvider = Provider.of<LabViewModel>(context);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      appBar: AppBar(
        title: LocaleKeys.labResults.tr(context: context).toText18(),
        backgroundColor: AppColors.bgScaffoldColor,
      ),
      body: Padding(
        padding: EdgeInsets.all(24.h),
        child: SingleChildScrollView(
          child: Consumer<LabViewModel>(
            builder: (context, model, child) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      LocaleKeys.labResults.tr(context: context).toText24(isBold: true),
                      Utils.buildSvgWithAssets(icon: AppAssets.search_icon).onPress(() {
                        if (model.isLabOrdersLoading) {
                          return;
                        } else {
                          showCommonBottomSheet(context,
                              child: SearchLabResultsContent(labSuggestionsList: model.labSuggestions),
                              callBackFunc: () {},
                              title: LocaleKeys.searchLabReport.tr(),
                              height: ResponsiveExtension.screenHeight,
                              isFullScreen: true,
                              isCloseButtonVisible: true);
                        }
                      }),
                    ],
                  ),
                  SizedBox(height: 16.h),
                  // Build Tab Bar
                  SizedBox(height: 16.h),
                  // Expandable list
                  ListView.builder(
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemCount: model.isLabOrdersLoading ? 5 : model.patientLabOrders.length,
                    itemBuilder: (context, index) {
                      final isExpanded = expandedIndex == index;
                      return model.isLabOrdersLoading
                          ? const MoviesShimmerWidget()
                          : AnimationConfiguration.staggeredList(
                              position: index,
                              duration: const Duration(milliseconds: 500),
                              child: SlideAnimation(
                                verticalOffset: 100.0,
                                child: FadeInAnimation(
                                  child: AnimatedContainer(
                                    duration: Duration(milliseconds: 300),
                                    curve: Curves.easeInOut,
                                    margin: EdgeInsets.symmetric(vertical: 8.h),
                                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 20.h, hasShadow: true),
                                    child: InkWell(
                                      onTap: () {
                                        setState(() {
                                          expandedIndex = isExpanded ? null : index;
                                        });
                                      },
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Padding(
                                            padding: EdgeInsets.all(16.h),
                                            child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                Row(
                                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                  children: [
                                                    CustomButton(
                                                      text: getLabOrderStatusText(model.patientLabOrders[index].status!),
                                                      onPressed: () {},
                                                      backgroundColor: getLabOrderStatusColor(model.patientLabOrders[index].status!).withOpacity(0.15),
                                                      borderColor: getLabOrderStatusColor(model.patientLabOrders[index].status!).withOpacity(0.01),
                                                      textColor: getLabOrderStatusColor(model.patientLabOrders[index].status!),
                                                      fontSize: 10,
                                                      fontWeight: FontWeight.w500,
                                                      borderRadius: 8,
                                                      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                                      height: 30.h,
                                                    ),
                                                    Icon(isExpanded ? Icons.expand_less : Icons.expand_more),
                                                  ],
                                                ),
                                                SizedBox(height: 8.h),
                                                Row(
                                                  children: [
                                                    Image.network(
                                                      model.patientLabOrders[index].doctorImageURL!,
                                                      width: 24.h,
                                                      height: 24.h,
                                                      fit: BoxFit.fill,
                                                    ).circle(100),
                                                    SizedBox(width: 4.h),
                                                    model.patientLabOrders[index].doctorName!.toText16(isBold: true)
                                                  ],
                                                ),
                                                SizedBox(height: 8.h),
                                                Row(
                                                  children: [
                                                    CustomButton(
                                                      text: DateUtil.formatDateToDate(DateUtil.convertStringToDate(model.patientLabOrders[index].createdOn), false),
                                                      onPressed: () {},
                                                      backgroundColor: AppColors.greyColor,
                                                      borderColor: AppColors.greyColor,
                                                      textColor: AppColors.blackColor,
                                                      fontSize: 12,
                                                      fontWeight: FontWeight.w500,
                                                      borderRadius: 8,
                                                      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                                      height: 24.h,
                                                    ),
                                                    SizedBox(width: 8.h),
                                                    CustomButton(
                                                      text: model.patientLabOrders[index].clinicDescription!,
                                                      onPressed: () {},
                                                      backgroundColor: AppColors.greyColor,
                                                      borderColor: AppColors.greyColor,
                                                      textColor: AppColors.blackColor,
                                                      fontSize: 12,
                                                      fontWeight: FontWeight.w500,
                                                      borderRadius: 8,
                                                      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                                      height: 24.h,
                                                    ),
                                                  ],
                                                ),
                                              ],
                                            ),
                                          ),
                                          AnimatedSwitcher(
                                            duration: Duration(milliseconds: 300),
                                            switchInCurve: Curves.easeIn,
                                            switchOutCurve: Curves.easeOut,
                                            transitionBuilder: (Widget child, Animation<double> animation) {
                                              return FadeTransition(
                                                opacity: animation,
                                                child: SizeTransition(
                                                  sizeFactor: animation,
                                                  axisAlignment: 0.0,
                                                  child: child,
                                                ),
                                              );
                                            },
                                            child: isExpanded
                                                ? Container(
                                                    key: ValueKey<int>(index),
                                                    padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 8.h),
                                                    child: Column(
                                                      crossAxisAlignment: CrossAxisAlignment.start,
                                                      children: [
                                                        ...model.patientLabOrders[index].testDetails!.map((detail) {
                                                          return Padding(
                                                            padding: EdgeInsets.only(bottom: 8.h),
                                                            child: '● ${detail.description}'.toText14(weight: FontWeight.w500),
                                                          );
                                                        }).toList(),
                                                        SizedBox(height: 16.h),
                                                        Row(
                                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                          children: [
                                                            SizedBox(),
                                                            CustomButton(
                                                              icon: AppAssets.view_report_icon,
                                                              iconColor: AppColors.primaryRedColor,
                                                              iconSize: 16.h,
                                                              text: LocaleKeys.viewReport.tr(context: context),
                                                              onPressed: () {},
                                                              backgroundColor: AppColors.secondaryLightRedColor,
                                                              borderColor: AppColors.secondaryLightRedColor,
                                                              textColor: AppColors.primaryRedColor,
                                                              fontSize: 14,
                                                              fontWeight: FontWeight.bold,
                                                              borderRadius: 12,
                                                              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                                              height: 40.h,
                                                            ),
                                                          ],
                                                        ),
                                                      ],
                                                    ),
                                                  )
                                                : SizedBox.shrink(key: ValueKey<int>(-index)),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            );
                    },
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  Color getLabOrderStatusColor(num status) {
    switch (status) {
      case 44:
        return AppColors.warningColorYellow;
      case 45:
        return AppColors.warningColorYellow;
      case 16:
        return AppColors.successColor;
      case 17:
        return AppColors.successColor;
      default:
        return AppColors.greyColor;
    }
  }

  String getLabOrderStatusText(num status) {
    switch (status) {
      case 44:
        return LocaleKeys.resultsPending.tr(context: context);
      case 45:
        return LocaleKeys.resultsPending.tr(context: context);
      case 16:
        return LocaleKeys.resultsAvailable.tr(context: context);
      case 17:
        return LocaleKeys.resultsAvailable.tr(context: context);
      default:
        return "";
    }
  }

  getLabSuggestions(LabViewModel model) {
    if (model.patientLabOrders.isEmpty) {
      return [];
    }
    return model.patientLabOrders.map((m) => m.testDetails).toList();
  }
}
