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/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.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/lab/lab_result_item_view.dart';
import 'package:hmg_patient_app_new/presentation/my_invoices/widgets/invoice_filter_bottom_sheet.dart';
import 'package:hmg_patient_app_new/presentation/my_invoices/widgets/invoice_list_card.dart';
import 'package:hmg_patient_app_new/presentation/my_invoices/widgets/pharmacy_invoice_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/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:open_filex/open_filex.dart';
import 'package:provider/provider.dart';

import '../../widgets/buttons/custom_button.dart';

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

  @override
  State<MyInvoicesList> createState() => _MyInvoicesListState();
}

class _MyInvoicesListState extends State<MyInvoicesList> {
  late MyInvoicesViewModel myInvoicesViewModel;

  @override
  void initState() {
    scheduleMicrotask(() {
      myInvoicesViewModel.setInvoicesListLoading();
      myInvoicesViewModel.getAllInvoicesList();
    });
    super.initState();
  }

  void _showHospitalFilterBottomSheet(BuildContext context) {
    myInvoicesViewModel.prepareFilterList(InvoiceFilterType.hospital);

    showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.selectHospital.tr(context: context),
      context,
      child: InvoiceFilterBottomSheet(
        title: LocaleKeys.hospital.tr(context: context),
        onItemSelected: (selectedHospital) {
          Navigator.pop(context);
          myInvoicesViewModel.filterInvoicesByHospital(selectedHospital);
        },
      ),
      isFullScreen: false,
      isCloseButtonVisible: true,
      hasBottomPadding: false,
      backgroundColor: AppColors.bottomSheetBgColor,
      callBackFunc: () {
        myInvoicesViewModel.clearFilterSearch();
      },
    );
  }

  void _showClinicFilterBottomSheet(BuildContext context) {
    myInvoicesViewModel.prepareFilterList(InvoiceFilterType.clinic);

    showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.selectClinic.tr(context: context),
      context,
      child: InvoiceFilterBottomSheet(
        title: LocaleKeys.clinic.tr(context: context),
        onItemSelected: (selectedClinic) {
          Navigator.pop(context);
          myInvoicesViewModel.filterInvoicesByClinic(selectedClinic);
        },
      ),
      isFullScreen: false,
      isCloseButtonVisible: true,
      hasBottomPadding: false,
      backgroundColor: AppColors.bottomSheetBgColor,
      callBackFunc: () {
        myInvoicesViewModel.clearFilterSearch();
      },
    );
  }

  void _showDoctorFilterBottomSheet(BuildContext context) {
    myInvoicesViewModel.prepareFilterList(InvoiceFilterType.doctor);

    showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.selectDoctor.tr(context: context),
      context,
      child: InvoiceFilterBottomSheet(
        title: LocaleKeys.doctor.tr(context: context),
        onItemSelected: (selectedDoctor) {
          Navigator.pop(context);
          myInvoicesViewModel.filterInvoicesByDoctor(selectedDoctor);
        },
      ),
      isFullScreen: false,
      isCloseButtonVisible: true,
      hasBottomPadding: false,
      backgroundColor: AppColors.bottomSheetBgColor,
      callBackFunc: () {
        myInvoicesViewModel.clearFilterSearch();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    myInvoicesViewModel = Provider.of<MyInvoicesViewModel>(context, listen: false);
    return CollapsingListView(
      title: LocaleKeys.invoiceList.tr(context: context),
      child: SingleChildScrollView(
        child: Consumer<MyInvoicesViewModel>(builder: (context, myInvoicesVM, child) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 16.h),
              CustomTabBar(
                activeTextColor: Color(0xffED1C2B),
                activeBackgroundColor: Color(0xffED1C2B).withValues(alpha: .1),
                initialIndex: 0,
                tabs: [
                  CustomTabBarModel(null, LocaleKeys.visitsOrders.tr(context: context)),
                  CustomTabBarModel(null, LocaleKeys.pharmacy.tr(context: context)),
                ],
                onTabChange: (index) {
                  myInvoicesVM.onTabChanged(index);
                  if (index == 1 && myInvoicesVM.allPharmacyInvoicesList.isEmpty) {
                    // Load pharmacy invoices when pharmacy tab is selected and list is empty
                    myInvoicesVM.getAllPharmacyInvoices();
                  }
                },
              ).paddingSymmetrical(24.h, 0.h),
              myInvoicesVM.selectedTabIndex == 0
                  ? Column(
                      children: [
                        SizedBox(height: 16.h),
                        Row(
                          children: [
                            CustomButton(
                              text: LocaleKeys.allInvoices.tr(context: context),
                              onPressed: () {
                                myInvoicesViewModel.filterInvoices(InvoiceFilterType.all);
                              },
                              backgroundColor: myInvoicesVM.currentFilter == InvoiceFilterType.all ? AppColors.bgRedLightColor : AppColors.whiteColor,
                              borderColor: myInvoicesVM.currentFilter == InvoiceFilterType.all
                                  ? AppColors.primaryRedColor
                                  : AppColors.textColor.withValues(alpha: 0.2),
                              textColor: myInvoicesVM.currentFilter == InvoiceFilterType.all ? AppColors.primaryRedColor : AppColors.blackColor,
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                              borderRadius: 10,
                              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                              height: 40.h,
                            ),
                            SizedBox(width: 8.h),
                            CustomButton(
                              text: LocaleKeys.hospitals.tr(context: context),
                              onPressed: () {
                                if (myInvoicesVM.getOriginalInvoicesList().isEmpty) return;
                                _showHospitalFilterBottomSheet(context);
                              },
                              backgroundColor:
                                  myInvoicesVM.currentFilter == InvoiceFilterType.hospital ? AppColors.bgRedLightColor : AppColors.whiteColor,
                              borderColor: myInvoicesVM.currentFilter == InvoiceFilterType.hospital
                                  ? AppColors.primaryRedColor
                                  : AppColors.textColor.withValues(alpha: 0.2),
                              textColor: myInvoicesVM.currentFilter == InvoiceFilterType.hospital ? AppColors.primaryRedColor : AppColors.blackColor,
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                              borderRadius: 10,
                              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                              height: 40.h,
                            ),
                            SizedBox(width: 8.h),
                            CustomButton(
                              text: LocaleKeys.clinics.tr(context: context),
                              onPressed: () {
                                if (myInvoicesVM.getOriginalInvoicesList().isEmpty) return;
                                _showClinicFilterBottomSheet(context);
                              },
                              backgroundColor:
                                  myInvoicesVM.currentFilter == InvoiceFilterType.clinic ? AppColors.bgRedLightColor : AppColors.whiteColor,
                              borderColor: myInvoicesVM.currentFilter == InvoiceFilterType.clinic
                                  ? AppColors.primaryRedColor
                                  : AppColors.textColor.withValues(alpha: 0.2),
                              textColor: myInvoicesVM.currentFilter == InvoiceFilterType.clinic ? AppColors.primaryRedColor : AppColors.blackColor,
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                              borderRadius: 10,
                              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                              height: 40.h,
                            ),
                            SizedBox(width: 8.h),
                            CustomButton(
                              text: LocaleKeys.doctors.tr(context: context),
                              onPressed: () {
                                if (myInvoicesVM.getOriginalInvoicesList().isEmpty) return;
                                _showDoctorFilterBottomSheet(context);
                              },
                              backgroundColor:
                                  myInvoicesVM.currentFilter == InvoiceFilterType.doctor ? AppColors.bgRedLightColor : AppColors.whiteColor,
                              borderColor: myInvoicesVM.currentFilter == InvoiceFilterType.doctor
                                  ? AppColors.primaryRedColor
                                  : AppColors.textColor.withValues(alpha: 0.2),
                              textColor: myInvoicesVM.currentFilter == InvoiceFilterType.doctor ? AppColors.primaryRedColor : AppColors.blackColor,
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                              borderRadius: 10,
                              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                              height: 40.h,
                            ),
                          ],
                        ).paddingSymmetrical(24.h, 0.h),
                        SizedBox(height: 16.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);
                            }).paddingSymmetrical(24.w, 0.h),
                      ],
                    )
                  : Column(
                      children: [
                        SizedBox(height: 16.h),
                        ListView.builder(
                            itemCount: myInvoicesVM.isPharmacyInvoicesLoading
                                ? 4
                                : myInvoicesVM.allPharmacyInvoicesList.isEmpty
                                    ? 1
                                    : myInvoicesVM.allPharmacyInvoicesList.length,
                            physics: NeverScrollableScrollPhysics(),
                            shrinkWrap: true,
                            padding: EdgeInsetsGeometry.zero,
                            itemBuilder: (context, index) {
                              return myInvoicesVM.isPharmacyInvoicesLoading
                                  ? LabResultItemView(onTap: () {}, labOrder: null, index: index, isLoading: true)
                                  : myInvoicesVM.allPharmacyInvoicesList.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: PharmacyInvoiceCard(
                                                  pharmacyInvoice: myInvoicesVM.allPharmacyInvoicesList[index],
                                                  onTap: () async {
                                                    // if (Utils.isVidaPlusProject(myInvoicesVM.allPharmacyInvoicesList[index].projectID ?? 0)) {
                                                    //   // For Vida+ projects, send email (if API is available)
                                                    //   showCommonBottomSheetWithoutHeight(
                                                    //     context,
                                                    //     child: Utils.getSuccessWidget(
                                                    //       loadingText: LocaleKeys.comingSoon.tr(context: context),
                                                    //     ),
                                                    //     callBackFunc: () {},
                                                    //     isFullScreen: false,
                                                    //     isCloseButtonVisible: true,
                                                    //     isAutoDismiss: true,
                                                    //   );
                                                    // } else {
                                                    // Download pharmacy invoice PDF
                                                    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.loadingText.tr(context: context));
                                                    myInvoicesViewModel.downloadPharmacyInvoicePDF(
                                                      setupId: myInvoicesVM.allPharmacyInvoicesList[index].setupId ?? "",
                                                      invoiceNo: myInvoicesVM.allPharmacyInvoicesList[index].invoiceNo ?? 0,
                                                      projectID: myInvoicesVM.allPharmacyInvoicesList[index].pharmacyProjectID ?? 0,
                                                      locationID: myInvoicesVM.allPharmacyInvoicesList[index].locationID ?? 0,
                                                      onError: (err) {
                                                        LoaderBottomSheet.hideLoader();
                                                        showCommonBottomSheetWithoutHeight(
                                                          context,
                                                          child: Utils.getErrorWidget(loadingText: err),
                                                          callBackFunc: () {},
                                                          isFullScreen: false,
                                                          isCloseButtonVisible: true,
                                                        );
                                                      },
                                                      onSuccess: (value) async {
                                                        LoaderBottomSheet.hideLoader();
                                                        if (myInvoicesViewModel.downloadPharmacyInvoicePDFBase64!.isNotEmpty) {
                                                          String path = await Utils.createFileFromString(
                                                              myInvoicesViewModel.downloadPharmacyInvoicePDFBase64!, "pdf");
                                                          try {
                                                            OpenFilex.open(path);
                                                          } catch (ex) {
                                                            showCommonBottomSheetWithoutHeight(
                                                              context,
                                                              child: Utils.getErrorWidget(loadingText: "Cannot open file"),
                                                              callBackFunc: () {},
                                                              isFullScreen: false,
                                                              isCloseButtonVisible: true,
                                                            );
                                                          }
                                                        }
                                                      },
                                                    );
                                                    // }
                                                  },
                                                ),
                                              ),
                                            ),
                                          ),
                                        )
                                      : Utils.getNoDataWidget(context);
                            }).paddingSymmetrical(24.w, 0.h),
                      ],
                    ),
            ],
          );
        }),
      ),
    );
  }
}
