import 'dart:async';
import 'dart:ui' as ui;

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/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/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/patient_lab_orders_response_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_result_via_clinic/LabResultByClinic.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/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/custom_tab_bar.dart';
import 'package:hmg_patient_app_new/widgets/date_range_selector/viewmodel/date_range_view_model.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

import 'alphabeticScroll.dart';

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

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

class _LabOrdersPageState extends State<LabOrdersPage> {
  late LabViewModel labProvider;
  late DateRangeSelectorRangeViewModel rangeViewModel;
  late AppState _appState;
  List<List<TestDetails>?> labSuggestions = [];
  int? expandedIndex;
  String? selectedFilterText = '';
  int activeIndex = 0;

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

  @override
  Widget build(BuildContext context) {
    labProvider = Provider.of<LabViewModel>(context, listen: false);
    rangeViewModel = Provider.of<DateRangeSelectorRangeViewModel>(context);
    _appState = getIt<AppState>();

    return CollapsingListView(
      title: LocaleKeys.labResults.tr(context: context),
      physics: activeIndex == 1 ? NeverScrollableScrollPhysics() : ScrollPhysics(),
      search: () async {
        if (labProvider.isLabOrdersLoading) {
          return;
        } else {
          String? value = await Navigator.of(context).push(
            CustomPageRoute(
              page: SearchLabResultsContent(labSuggestionsList: labProvider.labSuggestions),
              fullScreenDialog: true,
              direction: AxisDirection.down,
            ),
          );
          if (value != null) {
            selectedFilterText = value;
            labProvider.filterLabReports(value);
          }
        }
      },
      child: Consumer<LabViewModel>(
        builder: (context, labViewModel, child) {
          return SingleChildScrollView(
              physics: NeverScrollableScrollPhysics(),
              padding: EdgeInsets.all(24.h),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Expanded(
                        child: CustomTabBar(
                          activeTextColor: Color(0xffED1C2B),
                          activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1),
                          tabs: [
                            CustomTabBarModel(null, LocaleKeys.byVisit.tr()),
                            CustomTabBarModel(null, LocaleKeys.byTest.tr()),
                          ],
                          onTabChange: (index) {
                            activeIndex = index;
                            setState(() {});
                          },
                        ),
                      ),
                    ],
                  ),
                  if (activeIndex == 0)
                    Padding(
                      padding: EdgeInsets.symmetric(vertical: 10.h),
                      child: Row(
                        children: [
                          // CustomButton(
                          //   text: LocaleKeys.byClinic.tr(context: context),
                          //   onPressed: () {
                          //     labViewModel.setIsSortByClinic(true);
                          //   },
                          //   backgroundColor: labViewModel.isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor,
                          //   borderColor: labViewModel.isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2),
                          //   textColor: labViewModel.isSortByClinic ? AppColors.primaryRedColor : AppColors.blackColor,
                          //   fontSize: 12.f,
                          //   isBold: true,
                          //   borderRadius: 10,
                          //   padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                          //   height: 40.h,
                          // ),
                          // SizedBox(width: 8.h),
                          // CustomButton(
                          //   text: LocaleKeys.byHospital.tr(context: context),
                          //   onPressed: () {
                          //     labViewModel.setIsSortByClinic(false);
                          //   },
                          //   backgroundColor: labViewModel.isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor,
                          //   borderColor: labViewModel.isSortByClinic ? AppColors.textColor.withValues(alpha: 0.2) : AppColors.primaryRedColor,
                          //   textColor: labViewModel.isSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor,
                          //   fontSize: 12,
                          //   isBold: true,
                          //   borderRadius: 10,
                          //   padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                          //   height: 40.h,
                          // ),
                        ],
                      ),
                    ),
                  SizedBox(height: 8.h),
                  selectedFilterText!.isNotEmpty
                      ? Column(
                          children: [
                            AppCustomChipWidget(
                              labelText: selectedFilterText!,
                              backgroundColor: AppColors.alertColor,
                              textColor: AppColors.whiteColor,
                              deleteIcon: AppAssets.close_bottom_sheet_icon,
                              deleteIconColor: AppColors.whiteColor,
                              deleteIconHasColor: true,
                              isEnglishOnly: true,
                              onDeleteTap: () {
                                selectedFilterText = "";
                                labProvider.filterLabReports("");
                              },
                            ),
                            SizedBox(height: 8.h),
                          ],
                        )
                      : SizedBox(),
                  activeIndex == 0
                      ? // By Visit - show grouped view when available
                      labViewModel.isLabOrdersLoading
                          ? ListView.builder(
                              shrinkWrap: true,
                              physics: AlwaysScrollableScrollPhysics(),
                              padding: EdgeInsets.zero,
                              itemCount: 5,
                              itemBuilder: (context, index) => LabResultItemView(
                                onTap: () {},
                                labOrder: null,
                                index: index,
                                isLoading: true,
                              ),
                            )
                          : (labViewModel.patientLabOrders.isNotEmpty
                              ? ListView.builder(
                                  shrinkWrap: true,
                                  physics: NeverScrollableScrollPhysics(),
                                  padding: EdgeInsets.zero,
                                  itemCount: labViewModel.filteredLabOrders.length,
                                  itemBuilder: (context, index) {
                                    final group = labViewModel.filteredLabOrders[index];
                                    final isExpanded = expandedIndex == index;
                                    return 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: [
                                                              Wrap(
                                                                direction: Axis.horizontal,
                                                                spacing: 4.h,
                                                                runSpacing: 4.h,
                                                                children: [
                                                                  AppCustomChipWidget(
                                                                    richText: Row(
                                                                      children: [
                                                                        "${group.testDetails!.length} ".toText10(
                                                                            color: AppColors.successColor,
                                                                            isEnglishOnly: true,
                                                                            weight: FontWeight.w600),
                                                                        LocaleKeys.tests
                                                                            .tr(context: context)
                                                                            .toText10(color: AppColors.successColor, weight: FontWeight.w600),
                                                                      ],
                                                                    ),
                                                                    labelText:
                                                                        "${group.testDetails!.length} ${LocaleKeys.tests.tr(context: context)}",
                                                                    backgroundColor: AppColors.successColor.withOpacity(0.1),
                                                                    textColor: AppColors.successColor,
                                                                  ),
                                                                  AppCustomChipWidget(
                                                                    labelText:
                                                                        "${_appState.isArabic() ? group.isInOutPatientDescriptionN : group.isInOutPatientDescription}",
                                                                    backgroundColor: AppColors.warningColorYellow.withOpacity(0.1),
                                                                    textColor: AppColors.warningColorYellow,
                                                                  )
                                                                ],
                                                              ),
                                                              Icon(isExpanded ? Icons.expand_less : Icons.expand_more),
                                                            ],
                                                          ),
                                                          SizedBox(height: 8.h),
                                                          Row(
                                                            mainAxisSize: MainAxisSize.min,
                                                            children: [
                                                              Image.network(
                                                                group.doctorImageURL ??
                                                                    "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png",
                                                                width: 24.w,
                                                                height: 24.h,
                                                                fit: BoxFit.cover,
                                                              ).circle(100),
                                                              SizedBox(width: 8.h),
                                                              Expanded(
                                                                  child: (group.doctorName ?? group.doctorNameEnglish ?? "")
                                                                      .toString()
                                                                      .toText14(isBold: true)),
                                                            ],
                                                          ),
                                                          SizedBox(height: 8.h),
                                                          Wrap(
                                                            direction: Axis.horizontal,
                                                            spacing: 4.h,
                                                            runSpacing: 4.h,
                                                            children: [
                                                              Directionality(
                                                                  textDirection: ui.TextDirection.ltr,
                                                                  child: AppCustomChipWidget(
                                                                    labelText: DateUtil.formatDateToDate(
                                                                        DateUtil.convertStringToDate(group.orderDate ?? ""), false),
                                                                    isEnglishOnly: true,
                                                                  )),
                                                              AppCustomChipWidget(
                                                                labelText: (group.projectName ?? ""),
                                                              ),
                                                              AppCustomChipWidget(
                                                                labelText: (group.clinicDescription ?? ""),
                                                              ),
                                                            ],
                                                          ),
                                                        ],
                                                      ),
                                                    ),
                                                    AnimatedSwitcher(
                                                      duration: Duration(milliseconds: 500),
                                                      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.w, vertical: 0.h),
                                                              child: Column(
                                                                children: [
                                                                  ListView.separated(
                                                                      shrinkWrap: true,
                                                                      physics: NeverScrollableScrollPhysics(),
                                                                      padding: EdgeInsets.zero,
                                                                      itemBuilder: (cxt, index) {
                                                                        PatientLabOrdersResponseModel order = group;
                                                                        return Column(
                                                                          crossAxisAlignment: CrossAxisAlignment.start,
                                                                          children: [
                                                                            "• ${order.testDetails![index].description!}"
                                                                                .toText14(isBold: true, isEnglishOnly: true),
                                                                            SizedBox(height: 4.h),
                                                                            (_appState.isArabic() ? order.testDetails![index].testDescriptionAr! : order.testDetails![index].testDescriptionEn!).toText12(
                                                                                isBold: true, color: AppColors.textColorLight, isEnglishOnly: true),
                                                                          ],
                                                                        ).paddingOnly(top: 16, bottom: 16);
                                                                      },
                                                                      separatorBuilder: (cxt, index) => Divider(
                                                                          color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h),
                                                                      itemCount: group.testDetails!.length > 3 ? 3 : group.testDetails!.length),
                                                                  SizedBox(height: 16.h),
                                                                  CustomButton(
                                                                    text: "${LocaleKeys.viewResults.tr()} (${group.testDetails!.length})",
                                                                    onPressed: () {
                                                                      labProvider.currentlySelectedPatientOrder = group;
                                                                      labProvider.getPatientLabResultByHospital(group);
                                                                      labProvider.getPatientSpecialResult(group);
                                                                      Navigator.of(context).push(
                                                                        CustomPageRoute(
                                                                          page: LabResultByClinic(labOrder: group),
                                                                        ),
                                                                      );
                                                                    },
                                                                    backgroundColor: AppColors.infoColor.withAlpha(20),
                                                                    borderColor: AppColors.infoColor.withAlpha(0),
                                                                    textColor: AppColors.infoColor,
                                                                    fontSize: (isFoldable || isTablet) ? 12.f : 14.f,
                                                                    isBold: true,
                                                                    borderRadius: 12.r,
                                                                    padding: EdgeInsets.fromLTRB(10.w, 0, 10.w, 0),
                                                                    height: 40.h,
                                                                    iconSize: 14.h,
                                                                    icon: AppAssets.view_report_icon,
                                                                    iconColor: AppColors.infoColor,
                                                                  ),
                                                                  SizedBox(height: 16.h),
                                                                ],
                                                              ),
                                                            )
                                                          : SizedBox.shrink(),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            ),
                                          ),
                                        ));
                                  },
                                )
                              : Utils.getNoDataWidget(context, noDataText: LocaleKeys.noLabResults.tr(context: context)))
                      : // By Test or other tabs keep existing behavior
                      (labViewModel.isLabOrdersLoading)
                          ? Column(
                              children: List.generate(
                                  5,
                                  (index) => LabResultItemView(
                                        onTap: () {},
                                        labOrder: null,
                                        index: index,
                                        isLoading: true,
                                      )),
                            )
                          : AlphabeticScroll(
                              alpahbetsAvailable: labViewModel.filteredIndexedCharacterForUniqueTest,
                              details: labViewModel.filteredUniqueTestsList,
                              labViewModel: labViewModel,
                              rangeViewModel: rangeViewModel,
                              appState: _appState,
                            )
                ],
              ));
        },
      ),
    );
  }

  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();
  }
}
