import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.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/enums.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/lab_order_by_test.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/chip/custom_chip_widget.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:hmg_patient_app_new/widgets/transitions/fade_page.dart';
import 'package:provider/provider.dart';
import 'package:hmg_patient_app_new/widgets/custom_tab_bar.dart';
import '../../widgets/appbar/collapsing_list_view.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 Scaffold(
        backgroundColor: AppColors.bgScaffoldColor,
        body: CollapsingListView(
          title: LocaleKeys.labResults.tr(),
          search: () async {
            final lavVM = Provider.of<LabViewModel>(context, listen: false);
            if (lavVM.isLabOrdersLoading) {
              return;
            } else {
              String? value = await Navigator.of(context).push(
                CustomPageRoute(
                  page: SearchLabResultsContent(labSuggestionsList: lavVM.labSuggestions),
                  fullScreenDialog: true,
                  direction: AxisDirection.down,
                ),
              );
              if (value != null) {
                selectedFilterText = value;
                lavVM.filterLabReports(value);
              }
            }
          },
          child: SingleChildScrollView(
            padding: EdgeInsets.all(24.h),
            physics: NeverScrollableScrollPhysics(),
            child: Consumer<LabViewModel>(
              builder: (context, model, child) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 16.h),
                    CustomTabBar(
                      activeTextColor: Color(0xffED1C2B),
                      activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1),
                      tabs: [
                        CustomTabBarModel(null, "By Visit".needTranslation),
                        CustomTabBarModel(null, "By Test".needTranslation),
                        // CustomTabBarModel(null, "Completed".needTranslation),
                      ],
                      onTabChange: (index) {
                        activeIndex = index;
                        setState(() {});
                      },
                    ),
                    SizedBox(height: 16.h),
                    selectedFilterText!.isNotEmpty
                        ? CustomChipWidget(
                            chipText: selectedFilterText!,
                            chipType: ChipTypeEnum.alert,
                            isSelected: true,
                          )
                        : SizedBox(),
                    activeIndex == 0
                        ? ListView.builder(
                            shrinkWrap: true,
                            physics: NeverScrollableScrollPhysics(),
                            padding: EdgeInsets.zero,
                            itemCount: model.isLabOrdersLoading
                                ? 5
                                : model.patientLabOrders.isNotEmpty
                                    ? model.patientLabOrders.length
                                    : 1,
                            itemBuilder: (context, index) {
                              final isExpanded = expandedIndex == index;
                              return model.isLabOrdersLoading
                                  ? LabResultItemView(
                                      onTap: () {},
                                      labOrder: null,
                                      index: index,
                                      isLoading: true,
                                    )
                                  : model.patientLabOrders.isNotEmpty
                                      ? AnimationConfiguration.staggeredList(
                                          position: index,
                                          duration: const Duration(milliseconds: 500),
                                          child: SlideAnimation(
                                            verticalOffset: 100.0,
                                            child: FadeInAnimation(
                                                child: LabResultItemView(
                                                    onTap: () {
                                                      model.currentlySelectedPatientOrder =
                                                          model.patientLabOrders[
                                                              index];
                                                    labProvider.getPatientLabResultByHospital(model.patientLabOrders[
                                                                    index]);
                                                        labProvider
                                                            .getPatientSpecialResult(
                                                                model.patientLabOrders[
                                                                    index]);
                                                      Navigator.push(
                                                          context,
                                                          CustomPageRoute(
                                                          page: LabResultByClinic(labOrder: model.patientLabOrders[index]),
                                                        ));
                                                    },
                                                    labOrder: model.patientLabOrders[index],
                                                    index: index,
                                                  isExpanded: isExpanded),
                                            ),
                                          ),
                                        )
                                      : Utils.getNoDataWidget(context, noDataText: "You don't have any lab results yet.".needTranslation);
                            },
                          )
                        : ListView.builder(
                            shrinkWrap: true,
                            physics: NeverScrollableScrollPhysics(),
                            padding: EdgeInsets.zero,
                            itemCount: model.isLabOrdersLoading
                                ? 5
                                : model.uniqueTests.toList().isNotEmpty
                                    ? model.uniqueTests.toList().length
                                    : 1,
                            itemBuilder: (context, index) {
                              final isExpanded = expandedIndex == index;
                              return model.isLabOrdersLoading
                                  ? LabResultItemView(
                                      onTap: () {},
                                      labOrder: null,
                                      index: index,
                                      isLoading: true,
                                    )
                                  : model.uniqueTests.toList().isNotEmpty
                                      ? AnimationConfiguration.staggeredList(
                                          position: index,
                                          duration: const Duration(milliseconds: 500),
                                          child: SlideAnimation(
                                            verticalOffset: 100.0,
                                            child: FadeInAnimation(
                                                child: LabOrderByTest(
                                                    appState: _appState,
                                                    onTap: () {
                                                      if (model.uniqueTests.toList()[index].model != null) {
                                                        rangeViewModel.flush();
                                                        model.getPatientLabResult(model.uniqueTests.toList()[index].model!, model.uniqueTests.toList()[index].description!,
                                                            (_appState.isArabic() ? model.uniqueTests.toList()[index].testDescriptionAr! : model.uniqueTests.toList()[index].testDescriptionEn!));
                                                      }
                                                    },
                                                    tests: model.uniqueTests.toList()[index],
                                                    index: index,
                                                isExpanded: isExpanded)),
                                      ),
                                        )
                                      : Utils.getNoDataWidget(context, noDataText: "You don't have any lab results yet.".needTranslation);
                            },
                          )
                  ],
                );
              },
            ),
          ),
        ));
  }

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