import 'dart:async';

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_sickleave_response_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.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/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:open_filex/open_filex.dart';
import 'package:provider/provider.dart';

import 'widgets/patient_sick_leave_card.dart';

import 'dart:ui' as ui;

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

  @override
  State<PatientSickleavesListPage> createState() => _PatientSickleavesListPageState();
}

class _PatientSickleavesListPageState extends State<PatientSickleavesListPage> {
  int? expandedIndex;
  late MedicalFileViewModel medicalFileViewModel;

  @override
  void initState() {
    scheduleMicrotask(() {
      medicalFileViewModel.setIsPatientSickLeaveListLoading(true);
      medicalFileViewModel.getPatientSickLeaveList();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    AppState appState = getIt.get<AppState>();
    medicalFileViewModel = Provider.of<MedicalFileViewModel>(context, listen: false);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        title: (!appState.isArabic()
            ? "${LocaleKeys.sick2.tr(context: context)} ${LocaleKeys.sickSubtitle.tr(context: context)}"
            : "${LocaleKeys.sickSubtitle.tr(context: context)} ${LocaleKeys.sick2.tr(context: context)}"),
        child: SingleChildScrollView(
          child: Consumer<MedicalFileViewModel>(builder: (context, model, child) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // SizedBox(height: 16.h),
                // Clinic & Hospital Sort
                // Row(
                //   children: [
                //     CustomButton(
                //       text: LocaleKeys.byClinic.tr(context: context),
                //       onPressed: () {
                //         model.setIsSickLeavesSortByClinic(true);
                //       },
                //       backgroundColor: model.isSickLeavesSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor,
                //       borderColor: model.isSickLeavesSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withValues(alpha: 0.2),
                //       textColor: model.isSickLeavesSortByClinic ? 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: () {
                //         model.setIsSickLeavesSortByClinic(false);
                //       },
                //       backgroundColor: model.isSickLeavesSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor,
                //       borderColor: model.isSickLeavesSortByClinic ? AppColors.textColor.withValues(alpha: 0.2) : AppColors.primaryRedColor,
                //       textColor: model.isSickLeavesSortByClinic ? 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: 20.h),
                // Expandable list
                ListView.builder(
                  itemCount: model.isPatientSickLeaveListLoading
                      ? 4
                      : model.patientSickLeaveList.isNotEmpty
                          ? model.patientSickLeaveList.length
                          : 1,
                  physics: NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  padding: const EdgeInsets.only(left: 0, right: 8),
                  itemBuilder: (context, index) {
                    final isExpanded = expandedIndex == index;
                    return model.isPatientSickLeaveListLoading
                        ? PatientSickLeaveCard(
                            patientSickLeavesResponseModel: PatientSickLeavesResponseModel(),
                            isLoading: true,
                          ).paddingSymmetrical(0.h, 12.h)
                        : model.patientSickLeaveList.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: Container(
                                          padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h),
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              AppCustomChipWidget(
                                                labelText:
                                                    "${getIt.get<AppState>().isArabic() ? model.patientSickLeaveList[index].isInOutPatientDescriptionN : model.patientSickLeaveList[index].isInOutPatientDescription}",
                                                backgroundColor: AppColors.warningColorYellow.withOpacity(0.1),
                                                textColor: AppColors.warningColorYellow,
                                              ),
                                              SizedBox(height: 16.h),
                                              Row(
                                                mainAxisSize: MainAxisSize.min,
                                                children: [
                                                  Utils.buildImgWithNetwork(
                                                    url: model.patientSickLeaveList[index].doctorImageURL!,
                                                    iconColor: AppColors.transparent,
                                                    width: 24.h,
                                                    height: 24.h,
                                                    fit: BoxFit.fill,
                                                  ).circle(100),
                                                  SizedBox(width: 8.h),
                                                  Expanded(child: model.patientSickLeaveList[index].doctorName!.toText14(isBold: true)),
                                                ],
                                              ),
                                              SizedBox(height: 8.h),
                                              Wrap(
                                                direction: Axis.horizontal,
                                                spacing: 6.h,
                                                runSpacing: 6.h,
                                                children: [
                                                  Directionality(
                                                    textDirection: ui.TextDirection.ltr,
                                                    child: AppCustomChipWidget(
                                                      labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(model.patientSickLeaveList[index].appointmentDate), false),
                                                      isEnglishOnly: true,
                                                    ),
                                                  ),
                                                  AppCustomChipWidget(
                                                    labelText: model.isSickLeavesSortByClinic ? model.patientSickLeaveList[index].projectName! : model.patientSickLeaveList[index].clinicName!,
                                                  ),
                                                  AppCustomChipWidget(
                                                    richText: Row(
                                                      mainAxisSize: MainAxisSize.min,
                                                      children: [
                                                        "${model.patientSickLeaveList[index].sickLeaveDays} ".toText10(isBold: true),
                                                        LocaleKeys.days.tr(context: context).toText10(isBold: true)
                                                      ],
                                                    ),
                                                    // labelText: "${model.patientSickLeaveList[index].sickLeaveDays} ${LocaleKeys.days.tr(context: context)}",
                                                    isEnglishOnly: true,
                                                  ),
                                                ],
                                              ),
                                              SizedBox(height: 12.h),
                                              Row(
                                                children: [
                                                  Expanded(
                                                    flex: 6,
                                                    child: CustomButton(
                                                      text: LocaleKeys.downloadReport.tr(context: context),
                                                      onPressed: () async {
                                                        LoaderBottomSheet.showLoader();
                                                        await medicalFileViewModel.getPatientSickLeavePDF(model.patientSickLeaveList[index], appState.getAuthenticatedUser()!).then((val) async {
                                                          LoaderBottomSheet.hideLoader();
                                                          if (medicalFileViewModel.patientSickLeavePDFBase64.isNotEmpty) {
                                                            String path = await Utils.createFileFromString(medicalFileViewModel.patientSickLeavePDFBase64, "pdf");
                                                            try {
                                                              OpenFilex.open(path);
                                                            } catch (ex) {
                                                              debugPrint("Error opening file: $ex");
                                                            }
                                                          }
                                                        });
                                                      },
                                                      backgroundColor: AppColors.secondaryLightRedColor,
                                                      borderColor: AppColors.secondaryLightRedColor,
                                                      textColor: AppColors.primaryRedColor,
                                                      fontSize: 14,
                                                      isBold: true,
                                                      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),
                                            ],
                                          ),
                                          // Column(
                                          //   crossAxisAlignment: CrossAxisAlignment.start,
                                          //   children: [
                                          //     ...model.patientSickLeaveList[index].sickLeavesList!.map((sickLeave) {
                                          //       return Column(
                                          //         crossAxisAlignment: CrossAxisAlignment.start,
                                          //         children: [
                                          //           Row(
                                          //             mainAxisSize: MainAxisSize.min,
                                          //             children: [
                                          //               Image.network(
                                          //                 sickLeave.doctorImageURL!,
                                          //                 width: 24.h,
                                          //                 height: 24.h,
                                          //                 fit: BoxFit.fill,
                                          //               ).circle(100),
                                          //               SizedBox(width: 8.h),
                                          //               Expanded(child: sickLeave.doctorName!.toText14(isBold: true)),
                                          //             ],
                                          //           ),
                                          //           SizedBox(height: 8.h),
                                          //           Wrap(
                                          //             direction: Axis.horizontal,
                                          //             spacing: 6.h,
                                          //             runSpacing: 6.h,
                                          //             children: [
                                          //               AppCustomChipWidget(
                                          //                 labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(sickLeave.appointmentDate), false),
                                          //               ),
                                          //               AppCustomChipWidget(
                                          //                 labelText: model.isSickLeavesSortByClinic ? sickLeave.projectName! : sickLeave.clinicName!,
                                          //               ),
                                          //               AppCustomChipWidget(
                                          //                 labelText: "${sickLeave.sickLeaveDays} Days",
                                          //               ),
                                          //             ],
                                          //           ),
                                          //           SizedBox(height: 12.h),
                                          //           Row(
                                          //             children: [
                                          //               Expanded(
                                          //                 flex: 6,
                                          //                 child: CustomButton(
                                          //                   text: LocaleKeys.downloadReport.tr(context: context),
                                          //                   onPressed: () async {
                                          //                     LoaderBottomSheet.showLoader();
                                          //                     await medicalFileViewModel.getPatientSickLeavePDF(sickLeave, appState.getAuthenticatedUser()!).then((val) async {
                                          //                       LoaderBottomSheet.hideLoader();
                                          //                       if (medicalFileViewModel.patientSickLeavePDFBase64.isNotEmpty) {
                                          //                         String path = await Utils.createFileFromString(medicalFileViewModel.patientSickLeavePDFBase64, "pdf");
                                          //                         try {
                                          //                           OpenFilex.open(path);
                                          //                         } catch (ex) {
                                          //                           debugPrint("Error opening file: $ex");
                                          //                         }
                                          //                       }
                                          //                     });
                                          //                   },
                                          //                   backgroundColor: AppColors.secondaryLightRedColor,
                                          //                   borderColor: AppColors.secondaryLightRedColor,
                                          //                   textColor: AppColors.primaryRedColor,
                                          //                   fontSize: 14,
                                          //                   isBold: true,
                                          //                   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),
                                          //         ],
                                          //       );
                                          //     }),
                                          //   ],
                                          // ),
                                        )
                                        // 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: "${model.patientSickLeavesViewList[index].sickLeavesList!.length} ${LocaleKeys.sickSubtitle.tr(context: context)} 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),
                                        //             model.patientSickLeavesViewList[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: [
                                        //       //               ...model.patientSickLeavesViewList[index].sickLeavesList!.map((sickLeave) {
                                        //       //                 return Column(
                                        //       //                   crossAxisAlignment: CrossAxisAlignment.start,
                                        //       //                   children: [
                                        //       //                     Row(
                                        //       //                       mainAxisSize: MainAxisSize.min,
                                        //       //                       children: [
                                        //       //                         Image.network(
                                        //       //                           sickLeave.doctorImageURL!,
                                        //       //                           width: 24.h,
                                        //       //                           height: 24.h,
                                        //       //                           fit: BoxFit.fill,
                                        //       //                         ).circle(100),
                                        //       //                         SizedBox(width: 8.h),
                                        //       //                         Expanded(child: sickLeave.doctorName!.toText14(isBold: true)),
                                        //       //                       ],
                                        //       //                     ),
                                        //       //                     SizedBox(height: 8.h),
                                        //       //                     Wrap(
                                        //       //                       direction: Axis.horizontal,
                                        //       //                       spacing: 6.h,
                                        //       //                       runSpacing: 6.h,
                                        //       //                       children: [
                                        //       //                         AppCustomChipWidget(
                                        //       //                           labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(sickLeave.appointmentDate), false),
                                        //       //                         ),
                                        //       //                         AppCustomChipWidget(
                                        //       //                           labelText: model.isSickLeavesSortByClinic ? sickLeave.projectName! : sickLeave.clinicName!,
                                        //       //                         ),
                                        //       //                         AppCustomChipWidget(
                                        //       //                           labelText: "${sickLeave.sickLeaveDays} Days",
                                        //       //                         ),
                                        //       //                       ],
                                        //       //                     ),
                                        //       //                     SizedBox(height: 12.h),
                                        //       //                     Row(
                                        //       //                       children: [
                                        //       //                         Expanded(
                                        //       //                           flex: 6,
                                        //       //                           child: CustomButton(
                                        //       //                             text: LocaleKeys.downloadReport.tr(context: context),
                                        //       //                             onPressed: () async {
                                        //       //                               LoaderBottomSheet.showLoader();
                                        //       //                               await medicalFileViewModel.getPatientSickLeavePDF(sickLeave, appState.getAuthenticatedUser()!).then((val) async {
                                        //       //                                 LoaderBottomSheet.hideLoader();
                                        //       //                                 if (medicalFileViewModel.patientSickLeavePDFBase64.isNotEmpty) {
                                        //       //                                   String path = await Utils.createFileFromString(medicalFileViewModel.patientSickLeavePDFBase64, "pdf");
                                        //       //                                   try {
                                        //       //                                     OpenFilex.open(path);
                                        //       //                                   } catch (ex) {
                                        //       //                                     debugPrint("Error opening file: $ex");
                                        //       //                                   }
                                        //       //                                 }
                                        //       //                               });
                                        //       //                             },
                                        //       //                             backgroundColor: AppColors.secondaryLightRedColor,
                                        //       //                             borderColor: AppColors.secondaryLightRedColor,
                                        //       //                             textColor: AppColors.primaryRedColor,
                                        //       //                             fontSize: 14,
                                        //       //                             isBold: true,
                                        //       //                             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.youDontHaveAnySickLeavesYet.tr(context: context));
                  },
                ).paddingSymmetrical(24.h, 0.h),
                SizedBox(height: 24.h),
              ],
            );
          }),
        ),
      ),
    );
  }
}
