import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';

import '../Notifier/TransactionsProvider.dart';
import '../Utility/AppColors.dart';
import 'DashboardScreen.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: "Plus Jakarta Sans",
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
        ),

        /// ✅ Main Content
        body: provider.isLoading
            ? const Center(child: CircularProgressIndicator())
            : data == null
            ? const Center(child: Text("No transactions available"))
            : SingleChildScrollView(
          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: 15,
                        fontFamily: "Poppins",
                        fontWeight: FontWeight.w600,
                        color: Colors.black,
                      ),
                    ),
                    const SizedBox(height: 8),
                    ...items.map((txn) => _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: const TextStyle(
                              fontFamily: "Poppins",
                              fontWeight: FontWeight.w500,
                              fontSize: 13,
                              color: Colors.black,
                            ),
                          ),
                          Text(
                            "Bill Paid",
                            style: TextStyle(
                              fontFamily: "Poppins",
                              fontSize: 11,
                              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.w500,
                              fontSize: 13,
                              color: Colors.black,
                            ),
                          ),
                          Text(
                            "Bill Pending",
                            style: TextStyle(
                              fontFamily: "Poppins",
                              fontSize: 11,
                              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: 32,
                      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: const TextStyle(
                    fontFamily: "Poppins",
                    fontSize: 14,
                    color: Colors.black,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  date,
                  style: const TextStyle(
                    fontFamily: "Poppins",
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(width: 12),
          Text(
            amount,
            style: const TextStyle(
              fontFamily: "Poppins",
              fontSize: 14,
              color: Colors.black,
            ),
          ),
        ],
      ),
    );
  }

  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,
          flag: false,
        );
      },
    );
  }
}
