import 'dart:ui' as ui;

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/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/my_invoices/models/get_invoices_list_response_model.dart';
import 'package:hmg_patient_app_new/features/refund_request/refund_request_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/refund_request/refund_request_create_page.dart';
import 'package:hmg_patient_app_new/services/dialog_service.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:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

class InvoiceListCard extends StatelessWidget {
  final GetInvoicesListResponseModel getInvoicesListResponseModel;
  final Function? onTap;

  const InvoiceListCard({super.key, required this.getInvoicesListResponseModel, required this.onTap});

  void _handleRefundInvoiceTap(BuildContext context) {
    final invoiceNo = getInvoicesListResponseModel.invoiceNo;
    final projectId = getInvoicesListResponseModel.projectId;

    if (invoiceNo == null || projectId == null) {
      Navigator.of(context).push(
        CustomPageRoute(
          page: RefundRequestCreatePage(initialTabIndex: 0, invoice: getInvoicesListResponseModel),
        ),
      );
      return;
    }

    final viewModel = context.read<RefundRequestViewModel>();

    LoaderBottomSheet.showLoader();

    viewModel.checkIsRefundableInvoice(
      invoiceNo: invoiceNo,
      projectId: projectId,
      onSuccess: (result) {
        LoaderBottomSheet.hideLoader();
        if (result.isRefundable == true) {
          Navigator.of(context).push(
            CustomPageRoute(
              page: RefundRequestCreatePage(initialTabIndex: 0, invoice: getInvoicesListResponseModel),
            ),
          );
        } else {
          final message = result.message?.isNotEmpty == true ? result.message! : LocaleKeys.thisInvoiceIsNotEligibleForRefund.tr(context: context);
          getIt<DialogService>().showErrorBottomSheet(message: message);
        }
      },
      onError: (error) {
        LoaderBottomSheet.hideLoader();
        getIt<DialogService>().showErrorBottomSheet(message: error);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return 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(),
                  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: getInvoicesListResponseModel.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),
                            "${getInvoicesListResponseModel.decimalDoctorRate ?? '0.0'}".toText11(isBold: true, color: AppColors.textColor),
                          ],
                        ),
                      ).circle(100),
                    ),
                  ],
                ),
                SizedBox(width: 16.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      (getIt<AppState>().isArabic()
                              ? (getInvoicesListResponseModel.doctorNameN ??
                                  getInvoicesListResponseModel.doctorName ??
                                  LocaleKeys.doctor.tr(context: context))
                              : (getInvoicesListResponseModel.doctorName ??
                                  getInvoicesListResponseModel.doctorNameN ??
                                  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)}: ${getInvoicesListResponseModel.invoiceNo ?? '-'}",
                            labelPadding: EdgeInsetsDirectional.only(start: 6.w, end: 6.w),
                            isEnglishOnly: true,
                          ),
                          AppCustomChipWidget(
                            labelText: ((getInvoicesListResponseModel.clinicName ?? LocaleKeys.clinic.tr(context: context)).length > 15
                                ? '${(getInvoicesListResponseModel.clinicName ?? LocaleKeys.clinic.tr(context: context)).substring(0, 12)}...'
                                : (getInvoicesListResponseModel.clinicName ?? LocaleKeys.clinic.tr(context: context))),
                            labelPadding: EdgeInsetsDirectional.only(start: 4.w, end: 4.w),
                          ),
                          AppCustomChipWidget(
                            labelText: getInvoicesListResponseModel.projectName ?? LocaleKeys.hospital.tr(context: context),
                            labelPadding: EdgeInsetsDirectional.only(start: 6.w, end: 6.w),
                          ),
                          if (getInvoicesListResponseModel.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(getInvoicesListResponseModel.appointmentDate), false),
                                isEnglishOnly: true,
                              ),
                            ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
            if (onTap != null) ...[
              SizedBox(height: 16.h),
              Row(
                children: [
                  Expanded(
                    child: CustomButton(
                      // text: LocaleKeys.viewInvoiceDetails.tr(context: context),
                      text: Utils.isVidaPlusProject(getInvoicesListResponseModel.projectId ?? 0)
                          ? LocaleKeys.sendEmail.tr(context: context)
                          : LocaleKeys.downloadInvoice.tr(context: context),
                      onPressed: () {
                        if (onTap != null) {
                          onTap!();
                        }
                      },
                      backgroundColor: AppColors.primaryRedColor.withValues(alpha: 0.1),
                      borderColor: AppColors.primaryRedColor.withValues(alpha: 0.01),
                      textColor: AppColors.primaryRedColor,
                      fontSize: 14.f,
                      fontWeight: FontWeight.w600,
                      borderRadius: 12.r,
                      padding: EdgeInsets.symmetric(horizontal: 10.w),
                      height: 40.h,
                      iconSize: 14.h,
                    ),
                  ),
                  // if (getInvoicesListResponseModel.isAllowRefund == true) ...[
                  //   SizedBox(width: 8.w),
                  //   Expanded(
                  //     child: CustomButton(
                  //       text: LocaleKeys.requestRefund.tr(context: context),
                  //       onPressed: () {
                  //         _handleRefundInvoiceTap(context);
                  //       },
                  //       icon: AppAssets.refundIcon,
                  //       iconColor: AppColors.caloriesCalculatorColor,
                  //       backgroundColor: AppColors.blueColor.withValues(alpha: 0.14),
                  //       borderColor: AppColors.primaryRedColor.withValues(alpha: 0.01),
                  //       textColor: AppColors.caloriesCalculatorColor,
                  //       fontSize: 14.f,
                  //       fontWeight: FontWeight.w600,
                  //       borderRadius: 12.r,
                  //       padding: EdgeInsets.symmetric(horizontal: 10.w),
                  //       height: 40.h,
                  //       iconSize: 14.h,
                  //     ),
                  //   ),
                  // ]
                ],
              ),
            ],
          ],
        ),
      ),
    ).paddingOnly(bottom: 16.h);
  }
}
