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/enums.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.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_result_item_view.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:provider/provider.dart';

import '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;
  List<List<TestDetails>?> labSuggestions = [];
  int? expandedIndex;
  String? selectedFilterText = '';

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

  @override
  Widget build(BuildContext context) {
    labProvider = Provider.of<LabViewModel>(context);
    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(CupertinoPageRoute(fullscreenDialog: true, builder: (context) => SearchLabResultsContent(labSuggestionsList: lavVM.labSuggestions)));
              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: [
                    selectedFilterText!.isNotEmpty
                        ? CustomChipWidget(
                            chipText: selectedFilterText!,
                            chipType: ChipTypeEnum.alert,
                            isSelected: true,
                          )
                        : SizedBox(),
                    ListView.builder(
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      padding: EdgeInsets.zero,
                      itemCount: model.isLabOrdersLoading ? 5 : model.patientLabOrders.length,
                      itemBuilder: (context, index) {
                        final isExpanded = expandedIndex == index;
                        return model.isLabOrdersLoading
                            ? LabResultItemView(
                                onTap: () {},
                                labOrder: null,
                                index: index,
                                isLoading: true,
                              )
                            : AnimationConfiguration.staggeredList(
                                position: index,
                                duration: const Duration(milliseconds: 500),
                                child: SlideAnimation(
                                  verticalOffset: 100.0,
                                  child: FadeInAnimation(
                                      child: LabResultItemView(
                                          onTap: () {
                                            setState(() {
                                              expandedIndex = isExpanded ? null : index;
                                            });
                                          },
                                          labOrder: model.patientLabOrders[index],
                                          index: index,
                                          isExpanded: isExpanded)),
                                ),
                              );
                      },
                    ),
                  ],
                );
              },
            ),
          ),
        ));
  }

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