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/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/medical_file/medical_file_view_model.dart';
import 'package:hmg_patient_app_new/features/medical_file/models/patient_medical_response_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/medical_report/medical_report_request_page.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/presentation/medical_report/widgets/patient_medical_report_card.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/custom_tab_bar.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

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

  @override
  State<MedicalReportsPage> createState() => _MedicalReportsPageState();
}

class _MedicalReportsPageState extends State<MedicalReportsPage> {
  late MedicalFileViewModel medicalFileViewModel;

  @override
  Widget build(BuildContext context) {
    medicalFileViewModel = Provider.of<MedicalFileViewModel>(context, listen: false);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              title: "Medical Reports".needTranslation,
              child: SingleChildScrollView(
                child: Consumer<MedicalFileViewModel>(builder: (context, medicalFileVM, child) {
                  return Column(
                    children: [
                      SizedBox(height: 16.h),
                      Row(
                        children: [
                          CustomButton(
                            text: "Requested".needTranslation,
                            onPressed: () {
                              medicalFileViewModel.onMedicalReportTabChange(0);
                            },
                            backgroundColor: medicalFileVM.selectedMedicalReportsTabIndex == 0 ? AppColors.bgRedLightColor : AppColors.whiteColor,
                            borderColor: medicalFileVM.selectedMedicalReportsTabIndex == 0 ? AppColors.primaryRedColor : AppColors.textColor.withOpacity(0.2),
                            textColor: medicalFileVM.selectedMedicalReportsTabIndex == 0 ? AppColors.primaryRedColor : AppColors.blackColor,
                            fontSize: 12,
                            fontWeight: FontWeight.w500,
                            borderRadius: 10,
                            padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                            height: 40.h,
                          ),
                          SizedBox(width: 8.h),
                          CustomButton(
                            text: LocaleKeys.ready.tr(context: context),
                            onPressed: () {
                              medicalFileViewModel.onMedicalReportTabChange(1);
                            },
                            backgroundColor: medicalFileVM.selectedMedicalReportsTabIndex == 1 ? AppColors.bgRedLightColor : AppColors.whiteColor,
                            borderColor: medicalFileVM.selectedMedicalReportsTabIndex == 1 ? AppColors.primaryRedColor : AppColors.textColor.withOpacity(0.2),
                            textColor: medicalFileVM.selectedMedicalReportsTabIndex == 1 ? AppColors.primaryRedColor : AppColors.blackColor,
                            fontSize: 12,
                            fontWeight: FontWeight.w500,
                            borderRadius: 10,
                            padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                            height: 40.h,
                          ),
                          SizedBox(width: 8.h),
                          CustomButton(
                            text: LocaleKeys.cancelled.tr(context: context),
                            onPressed: () {
                              medicalFileViewModel.onMedicalReportTabChange(2);
                            },
                            backgroundColor: medicalFileVM.selectedMedicalReportsTabIndex == 2 ? AppColors.bgRedLightColor : AppColors.whiteColor,
                            borderColor: medicalFileVM.selectedMedicalReportsTabIndex == 2 ? AppColors.primaryRedColor : AppColors.textColor.withOpacity(0.2),
                            textColor: medicalFileVM.selectedMedicalReportsTabIndex == 2 ? AppColors.primaryRedColor : AppColors.blackColor,
                            fontSize: 12,
                            fontWeight: FontWeight.w500,
                            borderRadius: 10,
                            padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                            height: 40.h,
                          ),
                        ],
                      ).paddingSymmetrical(24.h, 0.h),
                      // CustomTabBar(
                      //   activeTextColor: Color(0xffED1C2B),
                      //   activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1),
                      //   tabs: [
                      //     CustomTabBarModel(null, "Requested".needTranslation),
                      //     CustomTabBarModel(null, "Ready".needTranslation),
                      //     CustomTabBarModel(null, "Cancelled".needTranslation),
                      //   ],
                      //   onTabChange: (index) {
                      //     medicalFileViewModel.onMedicalReportTabChange(index);
                      //   },
                      // ).paddingSymmetrical(24.h, 0.h),
                      ListView.separated(
                        padding: EdgeInsets.only(top: 24.h),
                        shrinkWrap: true,
                        physics: NeverScrollableScrollPhysics(),
                        itemCount: medicalFileViewModel.isPatientMedicalReportsListLoading
                            ? 3
                            : medicalFileViewModel.patientMedicalReportList.isNotEmpty
                                ? medicalFileViewModel.patientMedicalReportList.length
                                : 1,
                        itemBuilder: (context, index) {
                          return medicalFileViewModel.isPatientMedicalReportsListLoading
                              ? PatientMedicalReportCard(
                                  patientMedicalReportResponseModel: PatientMedicalReportResponseModel(),
                                  medicalFileViewModel: medicalFileVM,
                                  isLoading: true,
                                ).paddingSymmetrical(24.h, 0.h)
                              : medicalFileViewModel.patientMedicalReportList.isNotEmpty
                                  ? 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,
                                            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: true),
                                            child: PatientMedicalReportCard(
                                              patientMedicalReportResponseModel: medicalFileVM.patientMedicalReportList[index],
                                              medicalFileViewModel: medicalFileVM,
                                              isLoading: false,
                                            ),
                                          ).paddingSymmetrical(24.h, 0.h),
                                        ),
                                      ),
                                    )
                                  : Utils.getNoDataWidget(context, noDataText: "You don't have any medical reports yet.".needTranslation).paddingSymmetrical(24.h, 24.h);
                        },
                        separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h),
                      ),
                      SizedBox(height: 24.h),
                    ],
                  );
                }),
              ),
            ),
          ),
          Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 24.h,
              hasShadow: true,
            ),
            child: CustomButton(
              text: "Request medical report".needTranslation,
              onPressed: () async {
                LoaderBottomSheet.showLoader();
                await medicalFileViewModel.getPatientMedicalReportAppointmentsList(onSuccess: (val) async {
                  LoaderBottomSheet.hideLoader();
                  bool? value = await Navigator.of(context).push(
                    CustomPageRoute(
                      page: MedicalReportRequestPage(),
                      fullScreenDialog: true,
                      direction: AxisDirection.down,
                    ),
                  );
                  if (value != null) {
                    showConfirmRequestMedicalReportBottomSheet();
                  }
                }, onError: (err) {
                  LoaderBottomSheet.hideLoader();
                  showCommonBottomSheetWithoutHeight(
                    context,
                    child: Utils.getErrorWidget(loadingText: "You do not have any appointments to request a medical report.".needTranslation),
                    callBackFunc: () {},
                    isFullScreen: false,
                    isCloseButtonVisible: true,
                  );
                });
              },
              backgroundColor: AppColors.primaryRedColor,
              borderColor: AppColors.primaryRedColor,
              textColor: AppColors.whiteColor,
              fontSize: 16,
              fontWeight: FontWeight.w500,
              borderRadius: 12,
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              height: 45.h,
              icon: AppAssets.requests,
              iconColor: AppColors.whiteColor,
              iconSize: 20.h,
            ).paddingSymmetrical(24.h, 24.h),
          ),
        ],
      ),
    );
  }

  showConfirmRequestMedicalReportBottomSheet() {
    showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.notice.tr(context: context),
      context,
      child: Utils.getWarningWidget(
          loadingText: "Are you sure you want to request a medical report for this appointment?".needTranslation,
          isShowActionButtons: true,
          onCancelTap: () {
            Navigator.pop(context);
          },
          onConfirmTap: () async {
            Navigator.pop(context);
            LoaderBottomSheet.showLoader();
            await medicalFileViewModel.insertRequestForMedicalReport(onSuccess: (val) {
              LoaderBottomSheet.hideLoader();
              showCommonBottomSheetWithoutHeight(context, child: Utils.getSuccessWidget(loadingText: "Your medical report request has been successfully submitted.".needTranslation), callBackFunc: () {
                medicalFileViewModel.setIsPatientMedicalReportsLoading(true);
                medicalFileViewModel.onMedicalReportTabChange(0);
                medicalFileViewModel.getPatientMedicalReportList();
              });
            }, onError: (err) {
              LoaderBottomSheet.hideLoader();
              showCommonBottomSheetWithoutHeight(context, child: Utils.getErrorWidget(loadingText: err), callBackFunc: () {
                medicalFileViewModel.setIsPatientMedicalReportsLoading(true);
                medicalFileViewModel.onMedicalReportTabChange(0);
                medicalFileViewModel.getPatientMedicalReportList();
              });
            });
          }),
      callBackFunc: () {},
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }
}
