import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:gen_rentals/Screens/TransactionScreens/BillStatusToast.dart';
import 'package:provider/provider.dart';

import '../../Notifier/BillProvider.dart';
import '../../Notifier/TransactionsProvider.dart';
import '../../Utility/AppColors.dart';
import '../../Utility/CustomSnackbar.dart';
import '../BillScreens/BillDetailScreen.dart';
import '../DashboardScreen.dart';
import 'BillPendingToast.dart';


class TransactionsScreen extends StatefulWidget {
  final String sessionId;
  final String accId;
  const TransactionsScreen({
    super.key,
    required this.sessionId,
    required this.accId,
  });

  @override
  State<TransactionsScreen> createState() => _TransactionsScreenState();
}

class _TransactionsScreenState extends State<TransactionsScreen> {
  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      Provider.of<TransactionsProvider>(context, listen: false)
          .fetchRentalTransactions(widget.sessionId, widget.accId);
    });
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<TransactionsProvider>(context);
    final data = provider.transactionsResponse;

    return SafeArea(
      top: false,
      child: Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        appBar: AppBar(
          automaticallyImplyLeading: false,
          backgroundColor: Colors.white,
          title: Row(
            children: [
              InkResponse(
                onTap: () => Navigator.pop(context, true),
                child: SvgPicture.asset(
                  "assets/svg/continue_left_ic.svg",
                  height: 25,
                ),
              ),
              const SizedBox(width: 10),
              const Text(
                "Transactions",
                style: TextStyle(
                  fontSize: 16,
                  fontFamily: "Poppins",
                  fontWeight: FontWeight.w400,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
        ),

        /// ✅ Main Content
        body: provider.isLoading
            ? const Center(child: CircularProgressIndicator())
            : data == null
            ? const Center(child: Text("No transactions available"))
            : RefreshIndicator.adaptive(
          color: AppColors.subtitleText,
          onRefresh: () async {
            // Remove the delay and directly call the refresh
            await provider.fetchRentalTransactions(widget.sessionId, widget.accId);
          },
          child: SingleChildScrollView(
            physics: const AlwaysScrollableScrollPhysics(), // Important for RefreshIndicator
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildBalanceCard(data),
                const SizedBox(height: 16),

                /// 🗓️ Monthly Grouped Transactions
                ...data.transactions!.entries.map((entry) {
                  final month = entry.key;
                  final items = entry.value;
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const SizedBox(height: 12),
                      Text(
                        month,
                        style: const TextStyle(
                          fontSize: 14,
                          fontFamily: "Poppins",
                          fontWeight: FontWeight.w500,
                          color: Colors.black,
                        ),
                      ),
                      SizedBox(height: 8),
                      ...items.map((txn) => InkResponse(
                        onTap: () async {
                          final provider = Provider.of<TransactionsProvider>(context, listen: false);
                          await provider.fetchPaymentReceiptDetails(
                            widget.sessionId,
                            widget.accId,
                            txn.paymentId.toString(),
                          );

                          if (txn.type == "Credit") {
                            showDialog(
                              context: context,
                              builder: (context) => BillStatusToast(
                                sessionId: widget.sessionId,
                                accId: widget.accId,
                                ledgerId: txn.paymentId.toString(),
                              ),
                            );
                          } else if (txn.type == "Debit") {
                            showDialog(
                              context: context,
                              builder: (context) => BillPendingToast(
                                sessionId: widget.sessionId,
                                accId: widget.accId,
                                ledgerId: txn.paymentId.toString(),
                                onPayNow: () {
                                  Navigator.pop(context);
                                  // handle payment navigation
                                },
                              ),
                            );
                          }
                        },

                        child: _buildTransactionItem(
                          type: txn.type ?? "",
                          title: txn.purpose ?? "-",
                          date: txn.date ?? "",
                          amount: "₹${txn.amount ?? "0.00"}",
                        ),
                      )),
                    ],
                  );
                }),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 💰 Balance Card (Top Section)
  Widget _buildBalanceCard(data) {
    final balance = data.balanceAmount ?? "0";
    final credit = data.creditAmount ?? "0";
    final debit = data.debitAmount ?? "0";

    return Stack(
      children: [
        Container(
          width: double.infinity,
          padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 20),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Color(0xFAF3F3F3),
                Color(0xFAB5FFD1),
              ],
            ),
            borderRadius: BorderRadius.circular(16),
            boxShadow: [
              // BoxShadow(
              //   color: Colors.black.withOpacity(0.03),
              //   blurRadius: 8,
              //   offset: const Offset(0, 2),
              // )
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 140,),

              /// Credit / Debit Row
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  // ✅ Bill Paid
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Container(
                        height: 46,
                        width: 46,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(22),
                        ),
                        child: Center(
                          child: SvgPicture.asset(
                            "assets/svg/cross_up_arrow.svg",
                            height: 18,
                            width: 18,
                            fit: BoxFit.contain, // Ensures the SVG scales within bounds
                          ),
                        ),
                      ),

                      const SizedBox(width: 10),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "₹$credit",
                            style: TextStyle(
                              fontFamily: "Poppins",
                              fontWeight: FontWeight.w400,
                              fontSize: 14,
                              fontStyle: FontStyle.normal,
                              color: Colors.black,
                            ),
                          ),
                          Text(
                            "Bill Paid",
                            style: TextStyle(
                              fontFamily: "Poppins",
                              fontSize: 12,
                              fontStyle: FontStyle.normal,
                              fontWeight: FontWeight.w400,
                              color: Colors.black54,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),

                  const SizedBox(width: 40),

                  // ❌ Bill Pending
                  Row(
                    children: [
                      Container(
                        height: 46,
                        width: 46,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(22),
                        ),
                        child: Center(
                          child: SvgPicture.asset(
                            "assets/svg/cross_down_arrow.svg",
                            height: 18,
                            width: 18,
                            fit: BoxFit.contain, // Ensures the SVG scales within bounds
                          ),
                        ),
                      ),
                      const SizedBox(width: 10),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "₹$debit",
                            style: const TextStyle(
                              fontFamily: "Poppins",
                              fontWeight: FontWeight.w400,
                              fontSize: 14,
                              color: Colors.black,
                            ),
                          ),
                          Text(
                            "Bill Pending",
                            style: TextStyle(
                              fontFamily: "Poppins",
                              fontSize: 12,
                              fontStyle: FontStyle.normal,
                              fontWeight: FontWeight.w400,
                              color: Colors.black54,
                            ),
                          )
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),

        /// White overlay card (unchanged)
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(20),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  const Text(
                    "Balance Amount",
                    style: TextStyle(
                      fontFamily: "Poppins",
                      color: Color(0xFFF00000),
                      fontSize: 14,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                  const SizedBox(width: 4),
                  SvgPicture.asset(
                    "assets/svg/continue_ic.svg",
                    color: const Color(0xFFF00000),
                    height: 18,
                    width: 18,
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "₹$balance",
                    style: const TextStyle(
                      fontFamily: "Poppins",
                      color: Colors.black,
                      fontSize: 34,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  // InkResponse(
                  //   onTap: () => showPaymentBottomSheet(context),
                  //   child: Text(
                  //     "Pay Now",
                  //     style: TextStyle(
                  //       fontFamily: "Poppins",
                  //       color: Color(0xFF008CDE),
                  //       fontSize: 14,
                  //       fontWeight: FontWeight.w500,
                  //     ),
                  //   ),
                  // ),
                ],
              ),
              const SizedBox(height: 12),
              Text(
                "*Make sure to pay before you incur any fines.",
                style: TextStyle(
                  fontFamily: "Poppins",
                  color: Colors.grey.shade500,
                  fontSize: 12,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }



  /// 📋 Transaction Item
  Widget _buildTransactionItem({
    required String type,
    required String title,
    required String date,
    required String amount,
  }) {
    final isCredit = type.toLowerCase() == "credit";

    return Container(
      margin: const EdgeInsets.only(bottom: 10),
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
      ),
      child: Row(
        children: [
          CircleAvatar(
            radius: 20,
            backgroundColor:
            isCredit ? Colors.green.shade50 : Colors.red.shade50,
            child: SvgPicture.asset(
              isCredit
                  ? "assets/svg/cross_up_arrow.svg"
                  : "assets/svg/cross_down_arrow.svg",
              height: 18,
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontFamily: "Poppins",
                    fontSize: 14,
                    fontWeight: FontWeight.normal,
                    color: Colors.black,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  date,
                  style: TextStyle(
                    fontFamily: "Poppins",
                    fontSize: 12,
                    fontWeight: FontWeight.w400,
                    color: Colors.grey,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(width: 12),
          Text(
            amount,
            style: TextStyle(
              fontFamily: "Poppins",
              fontSize: 14,
              fontWeight: FontWeight.w400,
              color: Colors.black87,
            ),
          ),
        ],
      ),
    );
  }

  void showPaymentBottomSheet(
      BuildContext context, {
        String? payTotal = "4218",
        String? payBill = "2018",
      }) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true, // This is important
      backgroundColor: Colors.transparent,
      isDismissible: true,
      enableDrag: true,
      builder: (BuildContext context) {
        return PaymentBottomSheetContent(
          payTotal: payTotal,
          payBill: payBill,
          billFlag: false,
          partFlag: true,
        );
      },
    );
  }
}
