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/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/refund_request/models/resp_models/refund_request_list_response_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';

class RefundRequestDetailScreen extends StatelessWidget {
  final RefundInvoiceModel invoice;

  const RefundRequestDetailScreen({super.key, required this.invoice});

  String _formatDate(String? rawDate) {
    if (rawDate == null || rawDate.isEmpty) return '';
    try {
      final date = DateUtil.convertStringToDate(rawDate);
      return DateFormat('MMM dd, yyyy').format(date);
    } catch (_) {
      return rawDate;
    }
  }

  String rawDateForAdvance(String? rawDate) {
    if (rawDate == null || rawDate.isEmpty) return '';
    try {
      final date = DateTime.parse(rawDate);
      return DateFormat('MMM dd, yyyy').format(date);
    } catch (_) {
      return rawDate;
    }
  }

  Color getStatusColor(int status) {
    Color statusColor = AppColors.textColor;
    if (status == 3) {
      statusColor = AppColors.statusRejectedColor;
    } else if (status == 2) {
      statusColor = AppColors.statusCompletedColor;
    } else if (status == 1) {
      statusColor = AppColors.statusPendingColor;
    }
    return statusColor;
  }

  String getRefundDestinationIcon(String refundDestination) {
    String icon = "";

    if (refundDestination.toLowerCase().contains("wallet")) {
      icon = AppAssets.habibLogoOnly;
    } else if (refundDestination.toLowerCase().contains("bank")) {
      icon = AppAssets.bankIconOnly;
    }

    return icon;
  }

  Widget _buildInvoiceCard(BuildContext context, RefundInvoiceModel? invoice, {bool isLoading = false}) {
    final isInvoiceType = (invoice?.refundTypeId ?? 0) == 1;
    final isWalletType = (invoice?.refundTypeId ?? 0) == 2;
    final referenceNo = (invoice?.referenceNumber ?? '');
    final lastUpdated = _formatDate(invoice?.lastUpdated);
    final invoicePayload = invoice?.invoiceRequestPayload;
    final walletPayload = invoice?.walletRequestPayload;
    final totalProcedures = (invoicePayload?.proceduresList?.length.toString() ?? '');
    final statusName = (invoice?.requestStatusName ?? '');
    final statusId = (invoice?.requestStatusId ?? 1);
    final refundDestination = (invoice?.refundDestination ?? '');
    final refundType = invoice?.refundType ?? '';

    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: false),
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                AppCustomChipWidget(
                  icon: "",
                  labelText: statusName,
                  textColor: getStatusColor(statusId),
                  backgroundColor: getStatusColor(statusId).withValues(alpha: 0.2),
                ),
                " $lastUpdated"
                    .toText12(
                      color: AppColors.textColorLight,
                      isBold: false,
                    )
                    .toShimmer2(isShow: isLoading),
              ],
            ),
            SizedBox(height: 8.h),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                "${LocaleKeys.referenceNo.tr(context: context)}  $referenceNo"
                    .toText16(
                      color: AppColors.textColor,
                      isBold: true,
                    )
                    .toShimmer2(isShow: isLoading),
                // lastUpdated.toText12(color: AppColors.textColorLight).toShimmer2(isShow: isLoading),
              ],
            ),
            SizedBox(height: 8.h),
            Wrap(
              spacing: 6.w,
              runSpacing: 6.h,
              children: [
                if (!isLoading && refundDestination.isNotEmpty)
                  AppCustomChipWidget(icon: getRefundDestinationIcon(refundDestination), iconHasColor: false, labelText: refundDestination),
                if (refundType.isNotEmpty) AppCustomChipWidget(icon: "", labelText: "$refundType ${LocaleKeys.refund.tr()}"),
                if (isInvoiceType && invoicePayload != null) ...[
                  if (totalProcedures.isNotEmpty) AppCustomChipWidget(icon: "", labelText: "$totalProcedures ${LocaleKeys.procedures.tr()}"),
                  if (invoicePayload.project != null && invoicePayload.project!.isNotEmpty)
                    AppCustomChipWidget(icon: '', labelText: invoicePayload.project ?? ''),
                  if (invoicePayload.clinicName != null && invoicePayload.clinicName!.isNotEmpty)
                    AppCustomChipWidget(icon: '', labelText: invoicePayload.clinicName ?? ''),
                  if (invoicePayload.doctorName != null && invoicePayload.doctorName!.isNotEmpty)
                    AppCustomChipWidget(icon: '', labelText: invoicePayload.doctorName ?? ''),
                  // AppCustomChipWidget(icon: '', labelText: invoicePayload?.refundTypeName ?? ''),
                ] else if (isWalletType && walletPayload != null) ...[
                  AppCustomChipWidget(icon: '', labelText: walletPayload.project ?? ''),
                  // AppCustomChipWidget(icon: '', labelText: invoicePayload?.refundTypeName ?? ''),
                ],
              ],
            ),
            SizedBox(height: 16.h),
            if (isInvoiceType) ...[
              Utils.getPaymentAmountWithSymbol(
                isExpanded: false,
                ('${invoicePayload?.totalRefundAmount ?? 0}').toText20(isBold: true, color: AppColors.textColor),
                AppColors.textColor,
                14,
                isSaudiCurrency: true,
              )
            ] else ...[
              Utils.getPaymentAmountWithSymbol(
                isExpanded: false,
                ('${walletPayload?.totalRefundAmount ?? 0}').toText20(isBold: true, color: AppColors.textColor),
                AppColors.textColor,
                14,
                isSaudiCurrency: true,
              )
            ]
          ],
        ),
      ),
    );
  }

  Widget buildListDetails(BuildContext context, RefundInvoiceModel? invoice, {bool isLoading = false}) {
    final isInvoiceType = (invoice?.refundTypeId ?? 0) == 1;
    final isWalletType = (invoice?.refundTypeId ?? 0) == 2;
    final invoicePayload = invoice?.invoiceRequestPayload;
    final walletPayload = invoice?.walletRequestPayload;

    bool shouldShowPadding = (isWalletType && walletPayload != null) || (isInvoiceType && invoicePayload != null);
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.r,
        hasShadow: false,
      ),
      child: Padding(
        padding: EdgeInsets.all(shouldShowPadding ? 16.w : 0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Summary info
            if (isInvoiceType && invoicePayload != null) ...[
              // Procedures header
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  LocaleKeys.procedure.tr(context: context).toText12(color: AppColors.textColor, isBold: true),
                  LocaleKeys.amountOnly.tr(context: context).toText12(color: AppColors.textColor, isBold: true),
                ],
              ),
              SizedBox(height: 16.h),
              Divider(color: AppColors.bottomNAVBorder, height: 1, thickness: 1),
              SizedBox(height: 16.h),
              if (invoicePayload.proceduresList != null && invoicePayload.proceduresList!.isNotEmpty)
                ...invoicePayload.proceduresList!.map((p) => _buildProcedureRow(context, p)),
            ],
            if (isWalletType && walletPayload != null) ...[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(child: LocaleKeys.advanceNumber.tr(context: context).toText12(color: AppColors.textColor, isBold: true)),
                  SizedBox(
                    width: 80.w,
                    child:
                        LocaleKeys.amountOnly.tr(context: context).toText12(color: AppColors.textColor, isBold: true, textAlignment: TextAlign.end),
                  ),
                ],
              ),
              SizedBox(height: 16.h),
              Divider(color: AppColors.bottomNAVBorder, height: 1, thickness: 1),
              SizedBox(height: 16.h),
              if (walletPayload.advancesList != null && walletPayload.advancesList!.isNotEmpty)
                ...walletPayload.advancesList!.map((a) => _buildAdvanceRow(context, a)),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildProcedureRow(BuildContext context, InvoiceRefundProcedure procedure) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 6.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            flex: 3,
            child: (procedure.procedureName ?? '-').toText12(color: AppColors.textColor),
          ),
          SizedBox(width: 8.w),
          (procedure.patientPaidAmount?.toString() ?? '-').toText12(color: AppColors.textColor, isBold: true),
        ],
      ),
    );
  }

  Widget _buildAdvanceRow(BuildContext context, WalletAdvanceItem advance) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 6.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                (advance.advanceNo ?? '').toText12(color: AppColors.textColor),
                if (advance.advanceDate != null && advance.advanceDate!.isNotEmpty)
                  rawDateForAdvance(advance.advanceDate!).toText10(color: AppColors.greyTextColor),
              ],
            ),
          ),
          SizedBox(
            width: 80.w,
            child: (advance.balanceAmount?.toStringAsFixed(2) ?? '').toText12(color: AppColors.textColor, isBold: true, textAlignment: TextAlign.end),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return CollapsingListView(
      title: LocaleKeys.refundDetails.tr(context: context),
      isLeading: true,
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildInvoiceCard(context, invoice),
            SizedBox(height: 16.h),
            buildListDetails(context, invoice),
          ],
        ).paddingSymmetrical(24.w, 0),
      ),
    );
  }
}
