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/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/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/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/common_bottom_sheet.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:open_filex/open_filex.dart';
import 'package:provider/provider.dart';

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

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

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

  @override
  Widget build(BuildContext context) {
    AppState appState = getIt.get<AppState>();
    medicalFileViewModel = Provider.of<MedicalFileViewModel>(context, listen: false);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              title: LocaleKeys.medicalReports.tr(context: context),
              child: SingleChildScrollView(
                child: Consumer<MedicalFileViewModel>(builder: (context, medicalFileVM, child) {
                  return Column(
                    children: [
                      SizedBox(height: 16.h),
                      // Status filter tabs
                      // Row(
                      //   children: [
                      //     CustomButton(
                      //       text: LocaleKeys.byClinic.tr(context: context),
                      //       onPressed: () {
                      //         medicalFileVM.setIsMedicalReportsSortByClinic(true);
                      //       },
                      //       backgroundColor: medicalFileVM.isMedicalReportsSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor,
                      //       borderColor: medicalFileVM.isMedicalReportsSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2),
                      //       textColor: medicalFileVM.isMedicalReportsSortByClinic ? AppColors.primaryRedColor : AppColors.blackColor,
                      //       fontSize: 12,
                      //       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: () {
                      //         medicalFileVM.setIsMedicalReportsSortByClinic(false);
                      //       },
                      //       backgroundColor: medicalFileVM.isMedicalReportsSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor,
                      //       borderColor: medicalFileVM.isMedicalReportsSortByClinic ? AppColors.textColor.withValues(alpha: 0.2) : AppColors.primaryRedColor,
                      //       textColor: medicalFileVM.isMedicalReportsSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor,
                      //       fontSize: 12,
                      //       isBold: true,
                      //       borderRadius: 10,
                      //       padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                      //       height: 40.h,
                      //     ),
                      //   ],
                      // ).paddingSymmetrical(24.h, 0.h),
                      SizedBox(height: 8.h),
                      Row(
                        children: [
                          CustomButton(
                            text: LocaleKeys.requested.tr(context: context),
                            onPressed: () {
                              setState(() {
                                expandedIndex = null;
                              });
                              medicalFileViewModel.onMedicalReportTabChange(0);
                            },
                            backgroundColor: medicalFileVM.selectedMedicalReportsTabIndex == 0 ? AppColors.bgRedLightColor : AppColors.whiteColor,
                            borderColor: medicalFileVM.selectedMedicalReportsTabIndex == 0 ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2),
                            textColor: medicalFileVM.selectedMedicalReportsTabIndex == 0 ? AppColors.primaryRedColor : AppColors.blackColor,
                            fontSize: 12,
                            isBold: true,
                            borderRadius: 10,
                            padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                            height: 40.h,
                          ),
                          SizedBox(width: 8.h),
                          CustomButton(
                            text: LocaleKeys.ready.tr(context: context),
                            onPressed: () {
                              setState(() {
                                expandedIndex = null;
                              });
                              medicalFileViewModel.onMedicalReportTabChange(1);
                            },
                            backgroundColor: medicalFileVM.selectedMedicalReportsTabIndex == 1 ? AppColors.bgRedLightColor : AppColors.whiteColor,
                            borderColor: medicalFileVM.selectedMedicalReportsTabIndex == 1 ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2),
                            textColor: medicalFileVM.selectedMedicalReportsTabIndex == 1 ? AppColors.primaryRedColor : AppColors.blackColor,
                            fontSize: 12,
                            isBold: true,
                            borderRadius: 10,
                            padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                            height: 40.h,
                          ),
                          SizedBox(width: 8.h),
                          CustomButton(
                            text: LocaleKeys.cancelled.tr(context: context),
                            onPressed: () {
                              setState(() {
                                expandedIndex = null;
                              });
                              medicalFileViewModel.onMedicalReportTabChange(2);
                            },
                            backgroundColor: medicalFileVM.selectedMedicalReportsTabIndex == 2 ? AppColors.bgRedLightColor : AppColors.whiteColor,
                            borderColor: medicalFileVM.selectedMedicalReportsTabIndex == 2 ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2),
                            textColor: medicalFileVM.selectedMedicalReportsTabIndex == 2 ? AppColors.primaryRedColor : AppColors.blackColor,
                            fontSize: 12,
                            isBold: true,
                            borderRadius: 10,
                            padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                            height: 40.h,
                          ),
                        ],
                      ).paddingSymmetrical(24.h, 0.h),
                      SizedBox(height: 12.h),
                      // Clinic & Hospital Sort

                      // Expandable list
                      ListView.builder(
                        itemCount: medicalFileViewModel.isPatientMedicalReportsListLoading
                            ? 4
                            : medicalFileViewModel.patientMedicalReportList.isNotEmpty
                                ? medicalFileViewModel.patientMedicalReportsViewList.length
                                : 1,
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        padding: const EdgeInsets.only(left: 0, right: 8),
                        itemBuilder: (context, index) {
                          final isExpanded = expandedIndex == index;
                          return medicalFileViewModel.isPatientMedicalReportsListLoading
                              ? PatientMedicalReportCard(
                                  patientMedicalReportResponseModel: PatientMedicalReportResponseModel(),
                                  medicalFileViewModel: medicalFileVM,
                                  isLoading: true,
                                ).paddingSymmetrical(0.h, 8.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,
                                            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: "${medicalFileVM.patientMedicalReportsViewList[index].medicalReportsList!.length} Reports Available",
                                                              onPressed: () {},
                                                              backgroundColor: AppColors.greyColor,
                                                              borderColor: AppColors.greyColor,
                                                              textColor: AppColors.blackColor,
                                                              fontSize: 10,
                                                              isBold: true,
                                                              borderRadius: 8,
                                                              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                                              height: 30.h,
                                                            ),
                                                            Icon(isExpanded ? Icons.expand_less : Icons.expand_more),
                                                          ],
                                                        ),
                                                        SizedBox(height: 8.h),
                                                        medicalFileVM.patientMedicalReportsViewList[index].filterName!.toText16(isBold: true)
                                                      ],
                                                    ),
                                                  ),
                                                  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.h, vertical: 8.h),
                                                            child: Column(
                                                              crossAxisAlignment: CrossAxisAlignment.start,
                                                              children: [
                                                                ...medicalFileVM.patientMedicalReportsViewList[index].medicalReportsList!.map((report) {
                                                                  return Column(
                                                                    crossAxisAlignment: CrossAxisAlignment.start,
                                                                    children: [
                                                                      Row(
                                                                        mainAxisSize: MainAxisSize.min,
                                                                        children: [
                                                                          Utils.buildImgWithNetwork(
                                                                            url: report.doctorImageURL ?? "",
                                                                            iconColor: AppColors.transparent,
                                                                            width: 24.h,
                                                                            height: 24.h,
                                                                            fit: BoxFit.fill,
                                                                          ).circle(100),
                                                                          SizedBox(width: 8.h),
                                                                          Expanded(child: report.doctorName!.toText14(isBold: true)),
                                                                        ],
                                                                      ),
                                                                      SizedBox(height: 8.h),
                                                                      Wrap(
                                                                        alignment: WrapAlignment.start,
                                                                        direction: Axis.horizontal,
                                                                        spacing: 6.h,
                                                                        runSpacing: 6.h,
                                                                        children: [
                                                                          AppCustomChipWidget(
                                                                            labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(report.appointmentDate), false),
                                                                          ),
                                                                          AppCustomChipWidget(
                                                                            labelText: medicalFileVM.isMedicalReportsSortByClinic ? report.projectName! : report.clinicDescription!,
                                                                          ),
                                                                          report.statusDesc != null ? AppCustomChipWidget(
                                                                            labelText: report.statusDesc ?? "test",
                                                                          ) : SizedBox.shrink(),
                                                                        ],
                                                                      ),
                                                                      SizedBox(height: 8.h),
                                                                      Row(
                                                                        children: [
                                                                          if (medicalFileVM.selectedMedicalReportsTabIndex == 1)
                                                                            Expanded(
                                                                              flex: 6,
                                                                              child: CustomButton(
                                                                                text: LocaleKeys.downloadReport.tr(context: context),
                                                                                onPressed: () async {
                                                                                  LoaderBottomSheet.showLoader();
                                                                                  await medicalFileViewModel.getPatientMedicalReportPDF(report, appState.getAuthenticatedUser()!).then((val) async {
                                                                                    LoaderBottomSheet.hideLoader();
                                                                                    if (medicalFileViewModel.patientMedicalReportPDFBase64.isNotEmpty) {
                                                                                      String path = await Utils.createFileFromString(medicalFileViewModel.patientMedicalReportPDFBase64, "pdf");
                                                                                      try {
                                                                                        OpenFilex.open(path);
                                                                                      } catch (ex) {
                                                                                        debugPrint("Error opening file: $ex");
                                                                                      }
                                                                                    }
                                                                                  });
                                                                                },
                                                                                backgroundColor: AppColors.secondaryLightRedColor,
                                                                                borderColor: AppColors.secondaryLightRedColor,
                                                                                textColor: AppColors.primaryRedColor,
                                                                                fontSize: 14,
                                                                                fontWeight: FontWeight.w600,
                                                                                borderRadius: 12,
                                                                                padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                                                                height: 40.h,
                                                                                icon: AppAssets.download,
                                                                                iconColor: AppColors.primaryRedColor,
                                                                                iconSize: 14.h,
                                                                              ),
                                                                            ),
                                                                        ],
                                                                      ),
                                                                      SizedBox(height: 12.h),
                                                                      Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h),
                                                                      SizedBox(height: 12.h),
                                                                    ],
                                                                  );
                                                                }),
                                                              ],
                                                            ),
                                                          )
                                                        : SizedBox.shrink(),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    )
                                  : Utils.getNoDataWidget(context, noDataText: LocaleKeys.youDontHaveAnyMedicalReportsYet.tr(context: context))
                                      .paddingSymmetrical(24.h, 24.h);
                        },
                      ).paddingSymmetrical(24.h, 0.h),
                      SizedBox(height: 24.h),
                    ],
                  );
                }),
              ),
            ),
          ),
          Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 24.h,
              hasShadow: true,
            ),
            child: CustomButton(
              text: LocaleKeys.requestMedicalReport.tr(context: context),
              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: LocaleKeys.youDoNotHaveAnyAppointmentsToRequestMedicalReport.tr(context: context)),
                    callBackFunc: () {},
                    isFullScreen: false,
                    isCloseButtonVisible: true,
                  );
                });
              },
              backgroundColor: AppColors.primaryRedColor,
              borderColor: AppColors.primaryRedColor,
              textColor: Colors.white,
              fontSize: 16.f,
              fontWeight: FontWeight.w600,
              borderRadius: 12.r,
              height: 46.h,
              icon: AppAssets.requests,
              iconColor: Colors.white,
              iconSize: 20.h,
            ).paddingSymmetrical(24.h, 24.h),
          ),
        ],
      ),
    );
  }

  showConfirmRequestMedicalReportBottomSheet() {
    showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.notice.tr(context: context),
      context,
      child: Utils.getWarningWidget(
          loadingText: LocaleKeys.areYouSureYouWantToRequestMedicalReport.tr(context: context),
          isShowActionButtons: true,
          onCancelTap: () {
            Navigator.pop(context);
          },
          onConfirmTap: () async {
            Navigator.pop(context);
            LoaderBottomSheet.showLoader();
            await medicalFileViewModel.insertRequestForMedicalReport(onSuccess: (val) async{
              LoaderBottomSheet.hideLoader();
              showCommonBottomSheetWithoutHeight(context,
                  child: Utils.getSuccessWidget(loadingText: LocaleKeys.yourMedicalReportRequestSubmittedSuccessfully.tr(context: context)),
                  callBackFunc: () async{
                medicalFileViewModel.setIsPatientMedicalReportsLoading(true);
                medicalFileViewModel.onMedicalReportTabChange(0);
                medicalFileViewModel.getPatientMedicalReportList();

              });
              await Future.delayed(Duration(milliseconds: 2000)).then((value) {
                if (mounted) Navigator.pop(context);
              });
            }, 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,
      isAutoDismiss: false
    );
  }
}
