import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.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/int_extensions.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/my_invoices/models/get_invoice_details_response_model.dart';
import 'package:hmg_patient_app_new/features/my_invoices/models/get_invoices_list_response_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/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.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:open_filex/open_filex.dart';
import 'package:provider/provider.dart';

import 'dart:ui' as ui;

class MyInvoicesDetailsPage extends StatefulWidget {
  GetInvoiceDetailsResponseModel getInvoiceDetailsResponseModel;
  GetInvoicesListResponseModel getInvoicesListResponseModel;

  MyInvoicesDetailsPage({super.key, required this.getInvoiceDetailsResponseModel, required this.getInvoicesListResponseModel});

  @override
  State<MyInvoicesDetailsPage> createState() => _MyInvoicesDetailsPageState();
}

class _MyInvoicesDetailsPageState extends State<MyInvoicesDetailsPage> {
  late MyInvoicesViewModel myInvoicesViewModel;

  @override
  Widget build(BuildContext context) {
    myInvoicesViewModel = Provider.of<MyInvoicesViewModel>(context, listen: false);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              title: LocaleKeys.invoiceDetails.tr(context: context),
              downloadInvoice: Utils.isVidaPlusProject(widget.getInvoiceDetailsResponseModel.projectID ?? 0) ? null : () {
                LoaderBottomSheet.showLoader(loadingText: LocaleKeys.loadingText.tr(context: context));
                      myInvoicesViewModel.downloadInvoicePDF(
                        setupId: widget.getInvoicesListResponseModel.setupId!,
                        invoiceNo: widget.getInvoicesListResponseModel.invoiceNo!,
                        projectID: widget.getInvoicesListResponseModel.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: "Cannot open file"),
                                callBackFunc: () {},
                                isFullScreen: false,
                                isCloseButtonVisible: true,
                              );
                            }
                          }
                        },
                      );
                    },
              sendEmail: Utils.isVidaPlusProject(widget.getInvoiceDetailsResponseModel.projectID ?? 0) ? () async {
                LoaderBottomSheet.showLoader(loadingText: LocaleKeys.sendingEmailPleaseWait.tr(context: context));
                await myInvoicesViewModel.sendInvoiceEmail(
                    appointmentNo: widget.getInvoiceDetailsResponseModel.appointmentNo!,
                    projectID: widget.getInvoiceDetailsResponseModel.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,
                      );
                    });
              } : null,
              child: SingleChildScrollView(
                child: Padding(
                  padding: EdgeInsets.all(24.h),
                  child: Column(
                    children: [
                      Container(
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 20.h,
                          hasShadow: true,
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(14.h),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Wrap(
                                alignment: WrapAlignment.start,
                                direction: Axis.horizontal,
                                spacing: 6.w,
                                runSpacing: 6.h,
                                children: [
                                  AppCustomChipWidget(
                                    icon: AppAssets.walkin_appointment_icon,
                                    iconColor: AppColors.textColor,
                                    labelText: LocaleKeys.walkin.tr(context: context),
                                    textColor: AppColors.textColor,
                                  ),
                                  AppCustomChipWidget(
                                    labelText: LocaleKeys.outPatient.tr(context: context),
                                    backgroundColor: AppColors.warningColorYellow.withValues(alpha: 0.1),
                                    textColor: AppColors.warningColorYellow,
                                  ),
                                ],
                              ),
                              SizedBox(height: 16.h),
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Column(
                                    children: [
                                      Utils.buildImgWithNetwork(
                                        url: widget.getInvoiceDetailsResponseModel.doctorImageURL ?? 'https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png',
                                        iconColor: AppColors.transparent,
                                        width: 63.h,
                                        height: 63.h,
                                        fit: BoxFit.cover,
                                      ).circle(100.r),
                                      Transform.translate(
                                        offset: Offset(0.0, -20.h),
                                        child: Container(
                                          width: 40.w,
                                          height: 40.h,
                                          decoration: BoxDecoration(
                                            color: AppColors.whiteColor,
                                            shape: BoxShape.circle,
                                            border: Border.all(
                                              color: AppColors.scaffoldBgColor,
                                              width: 1.5.w,
                                            ),
                                          ),
                                          child: Column(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            children: [
                                              Utils.buildSvgWithAssets(icon: AppAssets.rating_icon, width: 15.w, height: 15.h, applyThemeColor: false),
                                              SizedBox(height: 2.h),
                                              "${widget.getInvoicesListResponseModel.decimalDoctorRate ?? '0.0'}".toText11(isBold: true, color: AppColors.textColor),
                                            ],
                                          ),
                                        ).circle(100),
                                      ),
                                    ],
                                  ),
                                  SizedBox(width: 16.w),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        (widget.getInvoiceDetailsResponseModel.doctorName ?? LocaleKeys.doctor.tr(context: context)).toText16(isBold: true),
                                        SizedBox(height: 8.h),
                                        Wrap(
                                          direction: Axis.horizontal,
                                          spacing: 6.w,
                                          runSpacing: 6.h,
                                          children: [
                                            AppCustomChipWidget(
                                              labelText: "${LocaleKeys.invoiceNo.tr(context: context)}: ${widget.getInvoiceDetailsResponseModel.invoiceNo ?? '-'}",
                                              labelPadding: EdgeInsetsDirectional.only(start: 6.w, end: 6.w),
                                              isEnglishOnly: true,
                                            ),
                                            AppCustomChipWidget(
                                              labelText: () {
                                                final clinicName = getIt<AppState>().isArabic()
                                                    ? (widget.getInvoiceDetailsResponseModel.clinicDescriptionN ?? widget.getInvoiceDetailsResponseModel.clinicDescription ?? LocaleKeys.clinic.tr(context: context))
                                                    : (widget.getInvoiceDetailsResponseModel.clinicDescription ?? widget.getInvoiceDetailsResponseModel.clinicDescriptionN ?? LocaleKeys.clinic.tr(context: context));
                                                return clinicName.length > 15 ? '${clinicName.substring(0, 12)}...' : clinicName;
                                              }(),
                                              labelPadding: EdgeInsetsDirectional.only(start: 4.w, end: 4.w),
                                            ),
                                            AppCustomChipWidget(
                                              labelText: widget.getInvoiceDetailsResponseModel.projectName ?? LocaleKeys.hospital.tr(context: context),
                                              labelPadding: EdgeInsetsDirectional.only(start: 6.w, end: 6.w),
                                            ),
                                            if (widget.getInvoiceDetailsResponseModel.appointmentDate != null)
                                              Directionality(
                                                textDirection: ui.TextDirection.ltr,
                                                child: AppCustomChipWidget(
                                                  labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: 6.w),
                                                  icon: AppAssets.doctor_calendar_icon,
                                                  labelText: DateUtil.formatDateToDate(DateUtil.convertStringToDate(widget.getInvoiceDetailsResponseModel.appointmentDate), false),
                                                  isEnglishOnly: true,
                                                ),
                                              ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(height: 16.h),
                      Container(
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 20.h,
                          hasShadow: true,
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(14.h),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              LocaleKeys.insurance.tr(context: context).toText16(isBold: true),
                              SizedBox(height: 16.h),
                              (getIt<AppState>().isArabic()
                                  ? (widget.getInvoiceDetailsResponseModel.groupNameN ?? widget.getInvoiceDetailsResponseModel.groupName ?? LocaleKeys.insurance.tr(context: context))
                                  : (widget.getInvoiceDetailsResponseModel.groupName ?? widget.getInvoiceDetailsResponseModel.groupNameN ?? LocaleKeys.insurance.tr(context: context))
                              ).toText14(isBold: true),
                              Row(
                                children: [
                                  Expanded(child: (widget.getInvoiceDetailsResponseModel.companyName ?? "").toText14(isBold: true)),
                                ],
                              ),
                              SizedBox(height: 12.h),
                              // Row(
                              //   children: [
                              //     AppCustomChipWidget(
                              //       labelText: "Insurance ID: ${widget.getInvoiceDetailsResponseModel.insuranceID ?? "-"}",
                              //       labelPadding: EdgeInsetsDirectional.only(start: 6.w, end: 6.w),
                              //       isEnglishOnly: true,
                              //     ),
                              //   ],
                              // ),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(height: 16.h),
                      Row(
                        mainAxisSize: MainAxisSize.max,
                        children: [
                          Expanded(
                            child: Container(
                              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                color: AppColors.whiteColor,
                                borderRadius: 20.h,
                                hasShadow: true,
                              ),
                              child: Padding(
                                padding: EdgeInsets.all(14.h),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    // Header row
                                    Row(
                                      children: [
                                        Expanded(flex: 3, child: LocaleKeys.name.tr().toText12(color: AppColors.textColor, isBold: true)),
                                        Expanded(flex: 1, child: LocaleKeys.quantity.tr().toText12(color: AppColors.textColor, isBold: true, isCenter: true)),
                                        Expanded(
                                            flex: 2, child: LocaleKeys.price.tr().toText12(color: AppColors.textColor, isBold: true, isCenter: true)),
                                        Expanded(
                                            flex: 2, child: LocaleKeys.total.tr().toText12(color: AppColors.textColor, isBold: true, isCenter: true)),
                                      ],
                                    ),
                                    SizedBox(height: 16.h),
                                    2.divider,
                                    SizedBox(height: 12.h),
                                    // Data rows
                                    ...widget.getInvoiceDetailsResponseModel.listConsultation!.map(
                                          (consultation) => Padding(
                                        padding: EdgeInsets.symmetric(vertical: 6.h),
                                        child: Row(
                                          children: [
                                            Expanded(flex: 3, child: (consultation.procedureName ?? '-').toText12(isBold: true)),
                                            Expanded(flex: 1, child: '${consultation.quantity ?? '-'}'.toText12(isBold: true, isCenter: true, isEnglishOnly: true)),
                                            Expanded(flex: 2, child: (NumberFormat.decimalPattern().format(consultation.totalPatientShare) ?? '-').toText12(isBold: true, isCenter: true, isEnglishOnly: true)),
                                            Expanded(flex: 2, child: (NumberFormat.decimalPattern().format(consultation.totalPatientShare) ?? '-').toText12(isBold: true, isCenter: true, isEnglishOnly: true)),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
          Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 24.h,
              hasShadow: false,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 24.h),
                LocaleKeys.totalBalance.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.h, 0.h),
                SizedBox(height: 17.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    LocaleKeys.amountBeforeTax.tr(context: context).toText14(isBold: true),
                    Utils.getPaymentAmountWithSymbol(
                        NumberFormat.decimalPattern().format(widget.getInvoiceDetailsResponseModel.listConsultation!.first.patientShare).toString().toText16(isBold: true, isEnglishOnly: true), AppColors.blackColor, 13,
                        isSaudiCurrency: true),
                  ],
                ).paddingSymmetrical(24.h, 0.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    LocaleKeys.vat15.tr(context: context).toText14(isBold: true, color: AppColors.greyTextColor),
                    Utils.getPaymentAmountWithSymbol(
                        NumberFormat.decimalPattern()
                            .format(widget.getInvoiceDetailsResponseModel.listConsultation!.first.patientVATAmount!)
                            .toString()
                            .toText14(isBold: true, color: AppColors.greyTextColor, isEnglishOnly: true),
                        AppColors.greyTextColor,
                        13,
                        isSaudiCurrency: true),
                  ],
                ).paddingSymmetrical(24.h, 0.h),
                SizedBox(height: 16.h),
                // Row(
                //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                //   children: [
                //     LocaleKeys.discount.tr(context: context).toText14(isBold: true),
                //     Utils.getPaymentAmountWithSymbol(
                //         NumberFormat.decimalPattern()
                //             .format(widget.getInvoiceDetailsResponseModel.listConsultation!.first.discountAmount!)
                //             .toString()
                //             .toText14(isBold: true, color: AppColors.primaryRedColor, isEnglishOnly: true),
                //         AppColors.primaryRedColor, 13,
                //         isSaudiCurrency: true),
                //   ],
                // ).paddingSymmetrical(24.h, 0.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    LocaleKeys.paid.tr(context: context).toText14(isBold: true),
                    Utils.getPaymentAmountWithSymbol(
                        NumberFormat.decimalPattern().format(widget.getInvoiceDetailsResponseModel.listConsultation!.first.totalPatientShare!).toString().toText14(isBold: true, color: AppColors.textColor, isEnglishOnly: true),
                        AppColors.textColor,
                        13,
                        isSaudiCurrency: true),
                  ],
                ).paddingSymmetrical(24.h, 0.h),
                SizedBox(height: 24.h),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
