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_export.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/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/habib_wallet/habib_wallet_view_model.dart';
import 'package:hmg_patient_app_new/features/my_invoices/my_invoices_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/habib_wallet/recharge_wallet_page.dart';
import 'package:hmg_patient_app_new/presentation/habib_wallet/widgets/wallet_balance_list.dart';
import 'package:hmg_patient_app_new/presentation/habib_wallet/withdraw_request_create_page.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.dart';
import 'package:hmg_patient_app_new/presentation/my_invoices/widgets/invoice_list_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/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 HabibWalletPage extends StatefulWidget {
  const HabibWalletPage({super.key});

  @override
  State<HabibWalletPage> createState() => _HabibWalletState();
}

class _HabibWalletState extends State<HabibWalletPage> {
  late HabibWalletViewModel habibWalletVM;
  late MyInvoicesViewModel myInvoicesViewModel;

  @override
  void initState() {
    scheduleMicrotask(() async {
      habibWalletVM.initHabibWalletProvider();
      habibWalletVM.getPatientBalanceAmount();
      habibWalletVM.getLakumAccountInformation();
      myInvoicesViewModel.setInvoicesListLoading();
      myInvoicesViewModel.getAllInvoicesList();
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    habibWalletVM = Provider.of<HabibWalletViewModel>(context, listen: false);
    myInvoicesViewModel = Provider.of<MyInvoicesViewModel>(context, listen: false);
    AppState appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        title: LocaleKeys.myWallet.tr(),
        child: Padding(
          padding: EdgeInsets.all(24.h),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: double.infinity,
                  height: 180.h,
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                      // color: AppColors.blackBgColor,
                      color: Color(0xFF2E3039),
                      borderRadius: 24.r,
                      hasShadow: true),
                  child: Padding(
                    padding: EdgeInsets.all(16.h),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                "${appState.getAuthenticatedUser()!.firstName!} ${appState.getAuthenticatedUser()!.lastName!}"
                                    .toText19(isBold: true, color: Colors.white),
                                "${LocaleKeys.fileno.tr(context: context)}: ${appState.getAuthenticatedUser()!.patientId!}"
                                    .toText14(isBold: true, color: AppColors.greyTextColor),
                              ],
                            ).expanded,
                            Utils.buildSvgWithAssets(icon: AppAssets.habiblogo, width: 24.h, height: 24.h, applyThemeColor: false),
                          ],
                        ),
                        Spacer(),
                        LocaleKeys.balanceAmount.tr(context: context).toText14(isBold: true, color: Colors.white),
                        SizedBox(height: 4.h),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Consumer<HabibWalletViewModel>(builder: (context, habibWalletVM, child) {
                              return Utils.getPaymentAmountWithSymbol2(habibWalletVM.habibWalletAmount,
                                      textColor: Colors.white, iconColor: Colors.white, iconSize: 16, isExpanded: false, letterSpacing: -1)
                                  .toShimmer2(isShow: habibWalletVM.isWalletAmountLoading, radius: 12.h, width: 80.h, height: 24.h);
                            }),
                            Transform.flip(
                              flipX: appState.isArabic(),
                              child: Utils.buildSvgWithAssets(
                                icon: AppAssets.arrow_forward,
                                height: 24.h,
                                width: 24.h,
                                iconColor: AppColors.whiteColor,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ).onPress(() {
                  showCommonBottomSheetWithoutHeight(
                    title: LocaleKeys.habibWallet.tr(context: context),
                    context,
                    // child: Utils.getSuccessWidget(loadingText: LocaleKeys.erAppointmentBookedSuccess.tr(context: context)),
                    child: HabibWalletBalanceList(),
                    callBackFunc: () {},
                    isFullScreen: false,
                    isCloseButtonVisible: true,
                  );
                }),
                SizedBox(height: 16.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Flexible(
                      child: CustomButton(
                        height: 40.h,
                        icon: AppAssets.recharge_icon,
                        iconSize: 24.w,
                        backgroundColor: AppColors.infoColor,
                        textColor: Colors.white,
                        text: LocaleKeys.recharge.tr(context: context),
                        borderWidth: 0.w,
                        fontWeight: FontWeight.w600,
                        borderColor: Colors.transparent,
                        padding: EdgeInsets.fromLTRB(4, 0, 12, 0),
                        fontSize: 14.f,
                        onPressed: () {
                          Navigator.of(context)
                              .push(CustomPageRoute(
                            page: RechargeWalletPage(),
                          ))
                              .then((val) {
                            habibWalletVM.initHabibWalletProvider();
                            habibWalletVM.getPatientBalanceAmount();
                            habibWalletVM.getLakumAccountInformation();
                          });
                        },
                      ),
                    ),
                    // SizedBox(width: 8.w),
                    // Flexible(
                    //   child: CustomButton(
                    //     height: 40.h,
                    //     icon: AppAssets.refundIcon,
                    //     iconSize: 24.w,
                    //     backgroundColor: AppColors.successColor,
                    //     textColor: Colors.white,
                    //     text: LocaleKeys.withdraw.tr(context: context),
                    //     borderWidth: 0.w,
                    //     fontWeight: FontWeight.w600,
                    //     borderColor: Colors.transparent,
                    //     padding: EdgeInsets.fromLTRB(4, 0, 12, 0),
                    //     fontSize: 14.f,
                    //     onPressed: () => Navigator.of(context).push(CustomPageRoute(page: WithdrawRequestCreatePage())),
                    //   ),
                    // ),
                  ],
                ),
                SizedBox(height: 24.h),
                // Container(
                //   decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                //     color: AppColors.whiteColor,
                //     borderRadius: 24.r,
                //     hasShadow: false,
                //   ),
                //   child: Consumer<HabibWalletViewModel>(builder: (context, habibWalletVM, child) {
                //     return ListView.separated(
                //       itemCount: habibWalletVM.habibWalletBalanceList.length,
                //       physics: NeverScrollableScrollPhysics(),
                //       padding: EdgeInsets.only(top: 8, bottom: 8),
                //       shrinkWrap: true,
                //       itemBuilder: (context, index) {
                //         return Row(
                //           mainAxisAlignment: MainAxisAlignment.spaceBetween,
                //           children: [
                //             Expanded(
                //                 child: habibWalletVM.habibWalletBalanceList[index].projectDescription!
                //                     .toText16(isBold: true, color: AppColors.textColor)),
                //             Utils.getPaymentAmountWithSymbol2(
                //                 habibWalletVM.habibWalletBalanceList[index].patientAdvanceBalanceAmount!, //did the changes because of negative value
                //                 textColor: AppColors.textColor,
                //                 iconColor: AppColors.textColor,
                //                 iconSize: 18.h,
                //                 isExpanded: false,
                //                 fontSize: 28.f,
                //                 fontWeight: FontWeight.w600,
                //                 letterSpacing: -1),
                //           ],
                //         ).paddingSymmetrical(0, 12.h);
                //       },
                //       separatorBuilder: (BuildContext context, int index) {
                //         return Divider(height: 1, color: AppColors.textColor.withAlpha(20));
                //       },
                //     ).paddingSymmetrical(16.h, 24.h).toShimmer2(isShow: habibWalletVM.isWalletAmountLoading);
                //   }),
                // ),
                // SizedBox(height: 16.h),
                // Invoices Section
                Consumer<MyInvoicesViewModel>(builder: (context, myInvoicesVM, child) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      LocaleKeys.invoiceHistory.tr(context: context).toText18(isBold: true, color: context.textColor),
                      SizedBox(height: 12.h),
                      ListView.builder(
                        itemCount: myInvoicesVM.isInvoicesListLoading
                            ? 4
                            : myInvoicesVM.allInvoicesList.isEmpty
                                ? 1
                                : myInvoicesVM.allInvoicesList.length,
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        padding: EdgeInsetsGeometry.zero,
                        itemBuilder: (context, index) {
                          return myInvoicesVM.isInvoicesListLoading
                              ? LabResultItemView(onTap: () {}, labOrder: null, index: index, isLoading: true)
                              : myInvoicesVM.allInvoicesList.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,
                                            child: InvoiceListCard(
                                              getInvoicesListResponseModel: myInvoicesVM.allInvoicesList[index],
                                              onTap: () async {
                                                if (Utils.isVidaPlusProject(myInvoicesVM.allInvoicesList[index].projectId ?? 0)) {
                                                  LoaderBottomSheet.showLoader(loadingText: LocaleKeys.sendingEmailPleaseWait.tr(context: context));
                                                  await myInvoicesViewModel.sendInvoiceEmail(
                                                      appointmentNo: myInvoicesVM.allInvoicesList[index].appointmentNo!,
                                                      projectID: myInvoicesVM.allInvoicesList[index].projectId!,
                                                      onSuccess: (val) {
                                                        LoaderBottomSheet.hideLoader();
                                                        showCommonBottomSheetWithoutHeight(context,
                                                            child: Utils.getSuccessWidget(
                                                                loadingText: LocaleKeys.emailSentSuccessfullyMessage.tr(context: context)),
                                                            callBackFunc: () {},
                                                            isFullScreen: false,
                                                            isCloseButtonVisible: true,
                                                            isAutoDismiss: true);
                                                      },
                                                      onError: (err) {
                                                        LoaderBottomSheet.hideLoader();
                                                        showCommonBottomSheetWithoutHeight(
                                                          context,
                                                          child: Utils.getErrorWidget(loadingText: err),
                                                          callBackFunc: () {},
                                                          isFullScreen: false,
                                                          isCloseButtonVisible: true,
                                                        );
                                                      });
                                                } else {
                                                  LoaderBottomSheet.showLoader(loadingText: LocaleKeys.loadingText.tr(context: context));
                                                  myInvoicesViewModel.downloadInvoicePDF(
                                                    setupId: myInvoicesVM.allInvoicesList[index].setupId!,
                                                    invoiceNo: myInvoicesVM.allInvoicesList[index].invoiceNo!,
                                                    projectID: myInvoicesVM.allInvoicesList[index].projectId!,
                                                    onError: (err) {
                                                      LoaderBottomSheet.hideLoader();
                                                      showCommonBottomSheetWithoutHeight(
                                                        context,
                                                        child: Utils.getErrorWidget(loadingText: err),
                                                        callBackFunc: () {},
                                                        isFullScreen: false,
                                                        isCloseButtonVisible: true,
                                                      );
                                                    },
                                                    onSuccess: (value) async {
                                                      LoaderBottomSheet.hideLoader();
                                                      if (myInvoicesViewModel.downloadInvoicePDFBase64!.isNotEmpty) {
                                                        String path =
                                                            await Utils.createFileFromString(myInvoicesViewModel.downloadInvoicePDFBase64!, "pdf");
                                                        try {
                                                          OpenFilex.open(path);
                                                        } catch (ex) {
                                                          showCommonBottomSheetWithoutHeight(
                                                            context,
                                                            child: Utils.getErrorWidget(loadingText: LocaleKeys.cannotOpenThisFile.tr()),
                                                            callBackFunc: () {},
                                                            isFullScreen: false,
                                                            isCloseButtonVisible: true,
                                                          );
                                                        }
                                                      }
                                                    },
                                                  );
                                                }
                                              },
                                            ),
                                          ),
                                        ),
                                      ),
                                    )
                                  : Utils.getNoDataWidget(context);
                        },
                      ),
                    ],
                  );
                }),
              ],
            ),
          ),
        ),
      ),
    );
  }
}


