import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:mobile_pos/Provider/transactions_provider.dart';
import 'package:mobile_pos/Screens/Loss_Profit/single_loss_profit_screen.dart';
import 'package:mobile_pos/const_commas.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:mobile_pos/model/print_transaction_model.dart';
import 'package:nb_utils/nb_utils.dart';

import '../../../../Provider/profile_provider.dart';
import '../../../../constant.dart';
import '../../../../currency.dart';
import '../../../../empty_screen_widget.dart';
import '../../../../generate_pdf.dart';
import '../../../../model/transition_model.dart';
import '../../../../thermal printing service/printing_provider/print_thermal_invoice_provider.dart';
import 'loss_profit_pdf.dart';

// Pagination Provider for Loss Profit Report
final lossProfitPaginationProvider =
    StateNotifierProvider<LossProfitPaginationNotifier, LossProfitPaginationState>((ref) {
  return LossProfitPaginationNotifier();
});

class LossProfitPaginationState {
  final int currentPage;
  final int itemsPerPage;
  final bool isLoading;
  final bool hasMore;
  final List<SalesTransitionModel> displayedTransactions;

  LossProfitPaginationState({
    this.currentPage = 1,
    this.itemsPerPage = 10,
    this.isLoading = false,
    this.hasMore = true,
    List<SalesTransitionModel>? displayedTransactions,
  }) : displayedTransactions = displayedTransactions ?? [];

  LossProfitPaginationState copyWith({
    int? currentPage,
    int? itemsPerPage,
    bool? isLoading,
    bool? hasMore,
    List<SalesTransitionModel>? displayedTransactions,
  }) {
    return LossProfitPaginationState(
      currentPage: currentPage ?? this.currentPage,
      itemsPerPage: itemsPerPage ?? this.itemsPerPage,
      isLoading: isLoading ?? this.isLoading,
      hasMore: hasMore ?? this.hasMore,
      displayedTransactions: displayedTransactions ?? this.displayedTransactions,
    );
  }
}

class LossProfitPaginationNotifier extends StateNotifier<LossProfitPaginationState> {
  LossProfitPaginationNotifier() : super(LossProfitPaginationState());

  void resetPagination() {
    state = LossProfitPaginationState();
  }

  void loadMoreTransactions(List<SalesTransitionModel> allTransactions,
      {DateTime? fromDate, DateTime? toDate}) {
    if (state.isLoading || !state.hasMore) return;

    state = state.copyWith(isLoading: true);

    // Filter transactions based on date range
    final filteredTransactions =
        _filterTransactions(allTransactions, fromDate: fromDate, toDate: toDate);

    final totalItems = filteredTransactions.length;
    final startIndex = (state.currentPage - 1) * state.itemsPerPage;
    final endIndex = startIndex + state.itemsPerPage;

    // Check if we have more items to load
    final hasMoreItems = endIndex < totalItems;

    // Get the next batch of transactions
    final nextBatch = endIndex <= totalItems
        ? filteredTransactions.sublist(startIndex, endIndex)
        : filteredTransactions.sublist(startIndex);

    // Update state
    final newDisplayedTransactions = [...state.displayedTransactions, ...nextBatch];

    state = state.copyWith(
      currentPage: state.currentPage + 1,
      isLoading: false,
      hasMore: hasMoreItems,
      displayedTransactions: newDisplayedTransactions,
    );
  }

  List<SalesTransitionModel> _filterTransactions(List<SalesTransitionModel> transactions,
      {DateTime? fromDate, DateTime? toDate}) {
    return transactions.where((transaction) {
      // Filter by date range if provided
      if (fromDate != null && toDate != null) {
        try {
          final purchaseDate = _safeParsePurchaseDate(transaction.purchaseDate);
          final normalizedFromDate = DateTime(fromDate.year, fromDate.month, fromDate.day);
          final normalizedToDate = DateTime(toDate.year, toDate.month, toDate.day);
          final normalizedPurchaseDate =
              DateTime(purchaseDate.year, purchaseDate.month, purchaseDate.day);

          final isInRange = (normalizedPurchaseDate.isAfter(normalizedFromDate) ||
                  normalizedPurchaseDate.isAtSameMomentAs(normalizedFromDate)) &&
              (normalizedPurchaseDate.isBefore(normalizedToDate) ||
                  normalizedPurchaseDate.isAtSameMomentAs(normalizedToDate));

          if (!isInRange) {
            return false;
          }
        } catch (e) {
          debugPrint('Error filtering transaction by date: $e');
          return false;
        }
      }

      return true;
    }).toList();
  }

  DateTime _safeParsePurchaseDate(String? dateString) {
    try {
      // Check if dateString is null or empty
      if (dateString == null || dateString.isEmpty || dateString.toLowerCase() == 'null') {
        return DateTime.now();
      }

      final cleanedDateString = dateString.trim();

      // Try parsing with common formats in order of likelihood
      try {
        return DateTime.parse(cleanedDateString);
      } catch (e) {
        final formats = [
          DateFormat("yyyy-MM-dd HH:mm:ss"),
          DateFormat("yyyy-MM-dd"),
          DateFormat("dd/MM/yyyy"),
          DateFormat("MM/dd/yyyy"),
          DateFormat("dd-MM-yyyy"),
          DateFormat("MM-dd-yyyy"),
        ];

        for (final format in formats) {
          try {
            return format.parse(cleanedDateString);
          } catch (e) {
            continue;
          }
        }

        // If all parsing fails, return current date
        return DateTime.now();
      }
    } catch (e) {
      return DateTime.now();
    }
  }
}

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

  @override
  _LossProfitReportState createState() => _LossProfitReportState();
}

class _LossProfitReportState extends State<LossProfitReport> {
  late TextEditingController fromDateTextEditingController;
  late TextEditingController toDateTextEditingController;
  late DateTime fromDate;
  late DateTime toDate;
  double totalProfit = 0;
  double totalLoss = 0;
  double totalSale = 0;
  bool isPicked = false;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    // Initialize dates with safe defaults
    fromDate = DateTime(DateTime.now().year, 1, 1); // Start of current year
    toDate = DateTime.now();
    fromDateTextEditingController = TextEditingController(text: _formatDate(fromDate));
    toDateTextEditingController = TextEditingController(text: _formatDate(toDate));

    // Add scroll listener for pagination
    _scrollController.addListener(_scrollListener);
  }

  @override
  void dispose() {
    fromDateTextEditingController.dispose();
    toDateTextEditingController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  void _scrollListener() {
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      // Load more data when scrolled to bottom
      _loadMoreData();
    }
  }

  void _loadMoreData() {
    final ref = ProviderScope.containerOf(context);
    final providerData = ref.read(transitionProvider);

    providerData.whenData((transactions) {
      // Filter out invalid transactions first
      final validTransactions = _getValidTransactions(transactions);
      ref.read(lossProfitPaginationProvider.notifier).loadMoreTransactions(
            validTransactions.reversed.toList(),
            fromDate: fromDate,
            toDate: toDate,
          );
    });
  }

  void _resetAndLoadData() {
    final ref = ProviderScope.containerOf(context);
    ref.read(lossProfitPaginationProvider.notifier).resetPagination();
    _loadMoreData();
  }

  String _formatDate(DateTime date) {
    try {
      return DateFormat.yMMMd().format(date);
    } catch (e) {
      return DateFormat.yMMMd().format(DateTime.now());
    }
  }

  DateTime _safeParsePurchaseDate(String? dateString) {
    try {
      // Check if dateString is null or empty
      if (dateString == null || dateString.isEmpty || dateString.toLowerCase() == 'null') {
        debugPrint('Warning: Invalid date string provided: "$dateString". Using current date.');
        return DateTime.now();
      }

      // Trim and clean the date string
      final cleanedDateString = dateString.trim();

      // Try parsing with common formats in order of likelihood
      try {
        return DateTime.parse(cleanedDateString);
      } catch (e) {
        // Try various common formats
        final formats = [
          DateFormat("yyyy-MM-dd HH:mm:ss"),
          DateFormat("yyyy-MM-dd"),
          DateFormat("dd/MM/yyyy"),
          DateFormat("MM/dd/yyyy"),
          DateFormat("dd-MM-yyyy"),
          DateFormat("MM-dd-yyyy"),
        ];

        for (final format in formats) {
          try {
            return format.parse(cleanedDateString);
          } catch (e) {
            continue;
          }
        }

        // If all parsing fails, return current date with warning
        debugPrint('Warning: Could not parse date: "$cleanedDateString". Using current date.');
        return DateTime.now();
      }
    } catch (e) {
      debugPrint('Error parsing date: $e');
      return DateTime.now();
    }
  }

  bool _isDateInRange(DateTime dateToCheck, DateTime startDate, DateTime endDate) {
    try {
      final normalizedStart = DateTime(startDate.year, startDate.month, startDate.day);
      final normalizedEnd = DateTime(endDate.year, endDate.month, endDate.day);
      final normalizedCheck = DateTime(dateToCheck.year, dateToCheck.month, dateToCheck.day);

      return (normalizedCheck.isAfter(normalizedStart) ||
              normalizedCheck.isAtSameMomentAs(normalizedStart)) &&
          (normalizedCheck.isBefore(normalizedEnd) ||
              normalizedCheck.isAtSameMomentAs(normalizedEnd));
    } catch (e) {
      debugPrint('Error in date range check: $e');
      return false;
    }
  }

  // Filter out transactions with invalid dates
  List<SalesTransitionModel> _getValidTransactions(List<SalesTransitionModel> allTransactions) {
    return allTransactions.where((transaction) {
      // Check if purchaseDate is valid
      if (transaction.purchaseDate == null ||
          transaction.purchaseDate!.isEmpty ||
          transaction.purchaseDate!.toLowerCase() == 'null') {
        debugPrint(
            'Skipping transaction with invalid date. Invoice: ${transaction.invoiceNumber ?? "N/A"}');
        return false;
      }
      return true;
    }).toList();
  }

  void _calculateTotals(List<SalesTransitionModel> transactions) {
    totalProfit = 0;
    totalLoss = 0;
    totalSale = 0;

    // Use only valid transactions for calculations
    final validTransactions = _getValidTransactions(transactions);

    for (var element in validTransactions) {
      try {
        final purchaseDate = _safeParsePurchaseDate(element.purchaseDate);

        // Safely handle null or invalid amounts
        final totalAmount = element.totalAmount ?? 0;
        final lossProfit = element.lossProfit ?? 0;

        if (!isPicked) {
          // Default to current month if no date range is picked
          if (purchaseDate.month == DateTime.now().month &&
              purchaseDate.year == DateTime.now().year) {
            if (lossProfit.isNegative) {
              totalLoss += lossProfit.abs();
            } else {
              totalProfit += lossProfit;
            }
            totalSale += totalAmount;
          }
        } else {
          // Use selected date range
          if (_isDateInRange(purchaseDate, fromDate, toDate)) {
            if (lossProfit.isNegative) {
              totalLoss += lossProfit.abs();
            } else {
              totalProfit += lossProfit;
            }
            totalSale += totalAmount;
          }
        }
      } catch (e) {
        debugPrint('Error calculating totals for transaction: $e');
        // Skip transactions with calculation errors
        continue;
      }
    }
  }

  List<SalesTransitionModel> _getFilteredTransactions(List<SalesTransitionModel> allTransactions) {
    // Use only valid transactions for filtering
    final validTransactions = _getValidTransactions(allTransactions);

    return validTransactions.where((element) {
      try {
        final purchaseDate = _safeParsePurchaseDate(element.purchaseDate);
        if (!isPicked) {
          return purchaseDate.month == DateTime.now().month &&
              purchaseDate.year == DateTime.now().year;
        } else {
          return _isDateInRange(purchaseDate, fromDate, toDate);
        }
      } catch (e) {
        debugPrint('Error filtering transaction: $e');
        return false;
      }
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(builder: (context, ref, __) {
      final providerData = ref.watch(transitionProvider);
      final personalData = ref.watch(profileDetailsProvider);
      final paginationState = ref.watch(lossProfitPaginationProvider);

      return providerData.when(
        data: (transaction) {
          // Filter out invalid transactions first
          final validTransactions = _getValidTransactions(transaction);
          final reTransaction = validTransactions.reversed.toList();

          // Calculate totals for all filtered transactions
          _calculateTotals(reTransaction);

          // Get all transactions that match the date filter for PDF generation
          final showAbleSaleTransactions = _getFilteredTransactions(reTransaction);

          // Initial load of data
          if (paginationState.displayedTransactions.isEmpty && !paginationState.isLoading) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              _resetAndLoadData();
            });
          }

          return personalData.when(
            data: (data) {
              return Scaffold(
                backgroundColor: kMainColor,
                appBar: AppBar(
                  iconTheme: const IconThemeData(color: kWhite),
                  title: Text(
                    lang.S.of(context).lossOrProfit,
                    style: GoogleFonts.poppins(
                      color: Colors.white,
                      fontSize: 20.0,
                    ),
                  ),
                  centerTitle: true,
                  backgroundColor: kMainColor,
                  elevation: 0.0,
                  actions: [
                    Padding(
                      padding: const EdgeInsets.only(right: 10.0),
                      child: Row(
                        children: [
                          Container(
                            height: 35,
                            width: 35,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(6.0),
                                border: Border.all(color: kMainColor),
                                color: Colors.white),
                            child: IconButton(
                              padding: EdgeInsets.zero,
                              visualDensity: const VisualDensity(horizontal: -4, vertical: -4),
                              onPressed: () async {
                                try {
                                  shareLossProfitPDF(
                                    personalInformationModel: data,
                                    transactions: showAbleSaleTransactions,
                                    fromDate: fromDate.toString(),
                                    toDate: toDate.toString(),
                                    saleAmount: totalSale.toStringAsFixed(2),
                                    profit: totalProfit.toStringAsFixed(2),
                                    loss: totalLoss.toStringAsFixed(2),
                                    context: context,
                                  );
                                } catch (e) {
                                  debugPrint('Error sharing PDF: $e');
                                  toast('Error sharing PDF: $e');
                                }
                              },
                              icon: const Icon(
                                Icons.share_outlined,
                                color: kMainColor,
                              ),
                            ),
                          ),
                          const SizedBox(width: 10.0),
                          Container(
                            height: 35,
                            width: 35,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(6.0),
                                border: Border.all(color: kMainColor),
                                color: Colors.white),
                            child: IconButton(
                              padding: EdgeInsets.zero,
                              visualDensity: const VisualDensity(horizontal: -4, vertical: -4),
                              onPressed: () async {
                                try {
                                  await GeneratePdf1().viewLossProfitPDf(
                                      data,
                                      showAbleSaleTransactions,
                                      fromDate.toString(),
                                      toDate.toString(),
                                      totalSale.toStringAsFixed(2),
                                      totalProfit.toStringAsFixed(2),
                                      totalLoss.toStringAsFixed(2),
                                      context);
                                } catch (e) {
                                  debugPrint('Error generating PDF: $e');
                                  toast('Error generating PDF: $e');
                                }
                              },
                              icon: const Icon(
                                Icons.download_outlined,
                                color: kMainColor,
                              ),
                            ),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
                body: Container(
                  alignment: Alignment.topCenter,
                  decoration: const BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                          topRight: Radius.circular(30), topLeft: Radius.circular(30))),
                  child: SingleChildScrollView(
                    controller: _scrollController,
                    child: Column(
                      children: [
                        Padding(
                          padding:
                              const EdgeInsets.only(right: 20.0, left: 20.0, top: 20, bottom: 10),
                          child: Row(
                            children: [
                              Expanded(
                                child: AppTextField(
                                  textFieldType: TextFieldType.NAME,
                                  readOnly: true,
                                  controller: fromDateTextEditingController,
                                  decoration: InputDecoration(
                                    floatingLabelBehavior: FloatingLabelBehavior.always,
                                    labelText: lang.S.of(context).formDate,
                                    border: const OutlineInputBorder(),
                                    suffixIcon: IconButton(
                                      onPressed: () async {
                                        try {
                                          final DateTime? picked = await showDatePicker(
                                            initialDate: fromDate,
                                            firstDate: DateTime(2015, 8),
                                            lastDate: DateTime(2101),
                                            context: context,
                                          );
                                          if (picked != null) {
                                            setState(() {
                                              fromDateTextEditingController.text =
                                                  _formatDate(picked);
                                              fromDate = picked;
                                              totalLoss = 0;
                                              totalProfit = 0;
                                              isPicked = true;
                                              _resetAndLoadData();
                                            });
                                          }
                                        } catch (e) {
                                          debugPrint('Error selecting from date: $e');
                                        }
                                      },
                                      icon: const Icon(FeatherIcons.calendar),
                                    ),
                                  ),
                                ),
                              ),
                              const SizedBox(width: 10),
                              Expanded(
                                child: AppTextField(
                                  textFieldType: TextFieldType.NAME,
                                  readOnly: true,
                                  controller: toDateTextEditingController,
                                  decoration: InputDecoration(
                                    floatingLabelBehavior: FloatingLabelBehavior.always,
                                    labelText: lang.S.of(context).toDate,
                                    border: const OutlineInputBorder(),
                                    suffixIcon: IconButton(
                                      onPressed: () async {
                                        try {
                                          final DateTime? picked = await showDatePicker(
                                            initialDate:
                                                toDate.isAfter(fromDate) ? toDate : fromDate,
                                            firstDate: fromDate,
                                            lastDate: DateTime(2101),
                                            context: context,
                                          );
                                          if (picked != null) {
                                            setState(() {
                                              toDateTextEditingController.text =
                                                  _formatDate(picked);
                                              toDate = picked;
                                              totalLoss = 0;
                                              totalProfit = 0;
                                              isPicked = true;
                                              _resetAndLoadData();
                                            });
                                          }
                                        } catch (e) {
                                          debugPrint('Error selecting to date: $e');
                                        }
                                      },
                                      icon: const Icon(FeatherIcons.calendar),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        paginationState.displayedTransactions.isNotEmpty ||
                                paginationState.isLoading
                            ? Column(
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.all(20.0),
                                    child: Container(
                                      height: 100,
                                      width: double.infinity,
                                      decoration: BoxDecoration(
                                          color: kMainColor.withValues(alpha: 0.1),
                                          border: Border.all(width: 1, color: kMainColor),
                                          borderRadius:
                                              const BorderRadius.all(Radius.circular(15))),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                                        children: [
                                          Column(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            crossAxisAlignment: CrossAxisAlignment.center,
                                            children: [
                                              Text(
                                                myFormat.format(totalProfit),
                                                style: const TextStyle(
                                                  color: Colors.green,
                                                  fontSize: 20,
                                                ),
                                              ),
                                              const SizedBox(height: 10),
                                              Text(
                                                lang.S.of(context).profit,
                                                style: const TextStyle(
                                                  color: Colors.black,
                                                  fontSize: 16,
                                                ),
                                              ),
                                            ],
                                          ),
                                          Container(
                                            width: 1,
                                            height: 60,
                                            color: kMainColor,
                                          ),
                                          Column(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            crossAxisAlignment: CrossAxisAlignment.center,
                                            children: [
                                              Text(
                                                myFormat.format(totalLoss),
                                                style: const TextStyle(
                                                  color: Colors.orange,
                                                  fontSize: 20,
                                                ),
                                              ),
                                              const SizedBox(height: 10),
                                              Text(
                                                lang.S.of(context).loss,
                                                style: const TextStyle(
                                                  color: Colors.black,
                                                  fontSize: 16,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                  ListView.builder(
                                    shrinkWrap: true,
                                    physics: const NeverScrollableScrollPhysics(),
                                    itemCount: paginationState.displayedTransactions.length +
                                        (paginationState.hasMore ? 1 : 0),
                                    itemBuilder: (context, index) {
                                      // Loading indicator at the end
                                      if (index == paginationState.displayedTransactions.length) {
                                        return paginationState.hasMore
                                            ? const Padding(
                                                padding: EdgeInsets.all(16.0),
                                                child: Center(
                                                  child: CircularProgressIndicator(),
                                                ),
                                              )
                                            : paginationState.displayedTransactions.isNotEmpty
                                                ? Padding(
                                                    padding: const EdgeInsets.all(16.0),
                                                    child: Center(
                                                      child: Text(
                                                        lang.S.of(context).noData,
                                                        style: const TextStyle(color: Colors.grey),
                                                      ),
                                                    ),
                                                  )
                                                : const SizedBox.shrink();
                                      }

                                      final transaction =
                                          paginationState.displayedTransactions[index];
                                      final purchaseDate =
                                          _safeParsePurchaseDate(transaction.purchaseDate);

                                      return GestureDetector(
                                        onTap: () {
                                          SingleLossProfitScreen(
                                            transactionModel: transaction,
                                          ).launch(context);
                                        },
                                        child: Column(
                                          children: [
                                            Container(
                                              padding: const EdgeInsets.all(20),
                                              width: context.width(),
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.spaceBetween,
                                                    children: [
                                                      Flexible(
                                                        child: Text(
                                                          (transaction.customerName?.isNotEmpty ??
                                                                  false)
                                                              ? transaction.customerName!
                                                              : transaction.customerPhone ??
                                                                  'Unknown Customer',
                                                          style: const TextStyle(fontSize: 16),
                                                          maxLines: 2,
                                                          overflow: TextOverflow.ellipsis,
                                                        ),
                                                      ),
                                                      Text(
                                                        '#${transaction.invoiceNumber ?? 'N/A'}',
                                                        style:
                                                            const TextStyle(color: Colors.black),
                                                      ),
                                                    ],
                                                  ),
                                                  const SizedBox(height: 10),
                                                  Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.spaceBetween,
                                                    children: [
                                                      Container(
                                                        padding: const EdgeInsets.all(8),
                                                        decoration: BoxDecoration(
                                                            color:
                                                                (transaction.dueAmount ?? 0) <= 0
                                                                    ? const Color(0xff0dbf7d)
                                                                        .withValues(alpha: 0.1)
                                                                    : const Color(0xFFED1A3B)
                                                                        .withValues(alpha: 0.1),
                                                            borderRadius: const BorderRadius.all(
                                                                Radius.circular(10))),
                                                        child: Text(
                                                          (transaction.dueAmount ?? 0) <= 0
                                                              ? lang.S.of(context).paid
                                                              : lang.S.of(context).unpaid,
                                                          style: TextStyle(
                                                              color:
                                                                  (transaction.dueAmount ?? 0) <= 0
                                                                      ? const Color(0xff0dbf7d)
                                                                      : const Color(0xFFED1A3B)),
                                                        ),
                                                      ),
                                                      Column(
                                                        crossAxisAlignment: CrossAxisAlignment.end,
                                                        children: [
                                                          Text(
                                                            _formatDate(purchaseDate),
                                                            style: const TextStyle(
                                                                color: Colors.grey),
                                                          ),
                                                          const SizedBox(height: 5),
                                                          Text(
                                                            DateFormat.jm().format(purchaseDate),
                                                            style: const TextStyle(
                                                                color: Colors.grey),
                                                          ),
                                                        ],
                                                      ),
                                                    ],
                                                  ),
                                                  const SizedBox(height: 5),
                                                  Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.spaceBetween,
                                                    children: [
                                                      Column(
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment.start,
                                                          children: [
                                                            Text(
                                                              '${lang.S.of(context).total} : $currency ${myFormat.format(transaction.totalAmount ?? 0)}',
                                                              style: const TextStyle(
                                                                  color: Colors.grey),
                                                            ),
                                                            const SizedBox(height: 5),
                                                            Text(
                                                              '${lang.S.of(context).profit} : $currency ${myFormat.format(transaction.lossProfit ?? 0)}',
                                                              style: const TextStyle(
                                                                  color: Colors.green,
                                                                  fontWeight: FontWeight.bold),
                                                            ).visible(!(transaction
                                                                    .lossProfit?.isNegative ??
                                                                true)),
                                                            Text(
                                                              '${lang.S.of(context).loss}: $currency ${myFormat.format((transaction.lossProfit ?? 0).abs())}',
                                                              style: const TextStyle(
                                                                  color: Colors.redAccent,
                                                                  fontWeight: FontWeight.bold),
                                                            ).visible(transaction
                                                                    .lossProfit?.isNegative ??
                                                                false),
                                                          ]),
                                                      Row(
                                                        children: [
                                                          IconButton(
                                                              onPressed: () async {
                                                                try {
                                                                  PrintTransactionModel model =
                                                                      PrintTransactionModel(
                                                                          transitionModel:
                                                                              transaction,
                                                                          personalInformationModel:
                                                                              data);
                                                                  ref
                                                                      .watch(
                                                                          thermalPrinterProvider)
                                                                      .printSalesThermalInvoiceNow(
                                                                          transaction: model,
                                                                          productList: model
                                                                              .transitionModel
                                                                              ?.productList,
                                                                          context: context);
                                                                } catch (e) {
                                                                  debugPrint('Error printing: $e');
                                                                  toast('Error printing: $e');
                                                                }
                                                              },
                                                              icon: const Icon(
                                                                FeatherIcons.printer,
                                                                color: Colors.grey,
                                                              )),
                                                          IconButton(
                                                              onPressed: () => toast(
                                                                  lang.S.of(context).comingSoon),
                                                              icon: const Icon(
                                                                FeatherIcons.share,
                                                                color: Colors.grey,
                                                              )).visible(false),
                                                        ],
                                                      ),
                                                    ],
                                                  ),
                                                ],
                                              ),
                                            ),
                                            Container(
                                              height: 0.5,
                                              width: context.width(),
                                              color: Colors.grey,
                                            )
                                          ],
                                        ),
                                      );
                                    },
                                  ),
                                ],
                              )
                            : const Padding(
                                padding: EdgeInsets.only(top: 60),
                                child: EmptyScreenWidget(),
                              ),
                      ],
                    ),
                  ),
                ),
              );
            },
            error: (e, stack) {
              return Text('Error loading profile: $e');
            },
            loading: () {
              return const Center(child: CircularProgressIndicator());
            },
          );
        },
        error: (e, stack) {
          return Text('Error loading transactions: $e');
        },
        loading: () {
          return const Center(child: CircularProgressIndicator());
        },
      );
    });
  }
}
