import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/commonProvider/accountDetailsProvider.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:generp/screens/commom/transactionDetails.dart';
import 'package:provider/provider.dart';

import '../../Models/commonModels/commonAccountdetailsResponse.dart';

class Accountslistdetails extends StatefulWidget {
  final accountID;

  const Accountslistdetails({super.key, this.accountID});

  @override
  State<Accountslistdetails> createState() => _AccountslistdetailsState();
}

class _AccountslistdetailsState extends State<Accountslistdetails> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var prov = Provider.of<Accountdetailsprovider>(context, listen: false);
      prov.accountdetailsAPIFunction(context, widget.accountID);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<Accountdetailsprovider>(
      builder: (context, provider, child) {
        final groupedData = provider.groupByDate(provider.ledgerList);
// Calculate total credit, debit, and balance
        double totalCredit = 0;
        double totalDebit = 0;
        double overallBalance = 0;

        for (var item in provider.ledgerList) {
          double credit = double.tryParse(item.creditAmount.toString()) ?? 0;
          double debit = double.tryParse(item.debitAmount.toString()) ?? 0;
          totalCredit += credit;
          totalDebit += debit;
        }
        overallBalance = totalDebit - totalCredit;

        return WillPopScope(
          child: Scaffold(
            appBar: appbar2(context, "Account Details",provider.resetValues,Container(
              padding: EdgeInsets.symmetric(horizontal: 5,vertical: 5),
              decoration: BoxDecoration(

                color: Color(0xFFE6F6FF),
                borderRadius: BorderRadius.circular(8),

              ),
              child: Row(
                children: [
                  SvgPicture.asset("assets/svg/fin_ic.svg",height: 12,),
                  SizedBox(width: 5,),
                  Text(overallBalance.toString()??"-",style: TextStyle(
                    fontSize: 12,
                  ),)
                ],
              ),
            )),
            resizeToAvoidBottomInset: true,
            backgroundColor: AppColors.scaffold_bg_color,
            body: SafeArea(
              child: SizedBox(
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(16)
                        ),
                        child: Row(
                          children: [
                            Expanded(
                              child: Container(
                                padding: EdgeInsets.symmetric(
                                  horizontal: 10,
                                  vertical: 15,
                                ),
                                margin: EdgeInsets.symmetric(
                                  horizontal: 10,
                                  vertical: 15,
                                ),
                                decoration: BoxDecoration(
                                  color: Color(0xFFFFEFEF),
                                  borderRadius: BorderRadius.circular(16),
                                ),
                                child: Column(
                                  crossAxisAlignment:
                                  CrossAxisAlignment.start,
                                  children: [
                                    RichText(
                                      text: TextSpan(
                                        children: [
                                          TextSpan(
                                            text: "${totalCredit}",
                                            style: TextStyle(
                                              color: Color(0xFFED3424),
                                              fontFamily:
                                              "JakartaRegular",
                                              fontSize: 25,
                                            ),
                                          ),

                                        ],
                                      ),
                                    ),
                                    Text(
                                      "credit",
                                      style: TextStyle(
                                        color: Color(0xFF818181),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            Expanded(
                              child: Container(
                                padding: EdgeInsets.symmetric(
                                  horizontal: 10,
                                  vertical: 15,
                                ),
                                margin: EdgeInsets.symmetric(
                                  horizontal: 10,
                                  vertical: 15,
                                ),
                                decoration: BoxDecoration(
                                  color: Color(0xFFFFEFEF),
                                  borderRadius: BorderRadius.circular(16),
                                ),
                                child: Column(
                                  crossAxisAlignment:
                                  CrossAxisAlignment.start,
                                  children: [
                                    RichText(
                                      text: TextSpan(
                                        children: [
                                          TextSpan(
                                            text: "${totalDebit}",
                                            style: TextStyle(
                                              color: Color(0xFFED3424),
                                              fontFamily:
                                              "JakartaRegular",
                                              fontSize: 25,
                                            ),
                                          ),

                                        ],
                                      ),
                                    ),
                                    Text(
                                      "debit",
                                      style: TextStyle(
                                        color: Color(0xFF818181),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Text(
                        "Account Details",
                        style: TextStyle(
                          fontSize: 16,
                          color: AppColors.grey_thick,
                          fontFamily: "JakartaMedium",
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 10,
                        ),
                        margin: EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 10,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(16),
                        ),
                        child: Column(
                          children: [
                            ...List.generate(12, (j) {
                              final headings = [
                                "Name",
                                "Address",
                                "Date",
                                "Bank Name",
                                "Bank Branch",
                                "Bank IFSC Code",
                                "Account Holder",
                                "Account Number",
                                "Bank UPI ID",
                                "State",
                                "District",
                                "Sub Locality",
                              ];

                              final subHeadings = [
                                provider.accountDetails.name ?? "-",
                                provider.accountDetails.address ?? "-",
                                provider.accountDetails.createdDatetime ?? "-",
                                provider.accountDetails.bankName ?? "-",
                                provider.accountDetails.bankBranchName ?? "-",
                                provider.accountDetails.bankIfscCode ?? "-",
                                provider.accountDetails.bankAccountHolderName ??
                                    "-",
                                provider.accountDetails.bankAccountNumber ?? "-",
                                provider.accountDetails.bankUpiId ?? "-",
                                provider.accountDetails.state ?? "-",
                                provider.accountDetails.district ?? "-",
                                provider.accountDetails.subLocality ?? "-",
                              ];
                              return Container(
                                padding: EdgeInsets.symmetric(vertical: 5),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Expanded(
                                      child: Text(
                                        headings[j],
                                        style: TextStyle(
                                          fontFamily: "JakartaMedium",
                                          fontSize: 14,
                                          color: AppColors.semi_black,
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 15),
                                    Expanded(
                                      child: Text(
                                        subHeadings[j] ?? "-",
                                        style: TextStyle(
                                          fontFamily: "JakartaMedium",
                                          fontSize: 14,
                                          color: AppColors.grey_thick,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              );
                            }),
                          ],
                        ),
                      ),
                      ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemCount: groupedData.keys.length,
                        itemBuilder: (context, index) {
                          String date = groupedData.keys.elementAt(index);
                          List<LedgerList> items = groupedData[date]!;

                          return Container(
                            padding: EdgeInsets.symmetric(vertical: 5),
                            margin: EdgeInsets.symmetric(horizontal: 10),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  padding: EdgeInsets.only(bottom: 5),
                                  child: Text(
                                    date,
                                    style: TextStyle(
                                      fontSize: 14,
                                      fontFamily: "JakartaMedium",
                                      color: Color(0xFF818181),
                                    ),
                                  ),
                                ),
                                ...items.map((item) {

                                  double running_balance = 0;
                                  int currentIndex = provider.ledgerList.indexOf(
                                    item,
                                  );
                                  for (var i = 0; i <= currentIndex; i++) {
                                    var ledgerItem = provider.ledgerList[i];
                                    double credit =
                                        double.tryParse(
                                          ledgerItem.creditAmount.toString(),
                                        ) ??
                                        0;
                                    double debit =
                                        double.tryParse(
                                          ledgerItem.debitAmount.toString(),
                                        ) ??
                                        0;
                                    running_balance += (debit - credit);
                                  }

                                  return Container(
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 10,
                                      vertical: 10,
                                    ),
                                    margin: EdgeInsets.symmetric(
                                      vertical: 5,
                                    ),
                                    decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.circular(16),
                                    ),
                                    child: Column(
                                      children: [
                                        Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.start,
                                          children: [
                                            Expanded(
                                              flex: 1,
                                              child: SizedBox(
                                                child:
                                                    item.type == "Credit"
                                                        ? Image.asset(
                                                          "assets/images/trans_debit.png",
                                                          height: 45,
                                                          width: 45,
                                                          fit: BoxFit.contain,
                                                        )
                                                        : Image.asset(
                                                          "assets/images/trans_credit.png",
                                                          height: 45,
                                                          width: 45,
                                                          fit: BoxFit.contain,
                                                        ),
                                              ),
                                            ),
                                            SizedBox(width: 10),
                                            Expanded(
                                              flex: 5,
                                              child: SizedBox(
                                                child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: [
                                                    Text(
                                                      item.description ?? "-",
                                                  maxLines: 2,
                                                  overflow: TextOverflow.ellipsis,
                                                      style: TextStyle(
                                                        fontFamily:
                                                            "JakartaMedium",
                                                        fontSize: 12,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            ),
                                            Spacer(),
                                            Expanded(
                                              flex: 3,
                                              child: SizedBox(
                                                child: RichText(
                                                  maxLines: 1,
                                                  textAlign: TextAlign.right,
                                                  overflow: TextOverflow.ellipsis,
                                                  text: TextSpan(

                                                    children: [
                                                      TextSpan(
                                                        text:
                                                            item.type == "Credit"
                                                                ? "-"
                                                                : "+",
                                                        style: TextStyle(
                                                          color: Color(
                                                            0xFF2D2D2D,
                                                          ),
                                                          fontSize: 13,
                                                          fontFamily:
                                                              "JakartaRegular",
                                                        ),
                                                      ),
                                                      TextSpan(
                                                        text:
                                                            "₹${item.type == "Credit" ? "${item.creditAmount}" : "${item.debitAmount}"}",
                                                        style: TextStyle(
                                                          color: Color(
                                                            0xFF2D2D2D,
                                                          ),
                                                          fontSize: 13,
                                                          fontFamily:
                                                              "JakartaMedium",
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                        Divider(
                                          thickness: 0.5,
                                          color: Color(0xFFd7d7d7),
                                        ),
                                        Row(
                                          children: [
                                            Expanded(child: Text("Balance",style: TextStyle(
                                              fontSize: 13,
                                              color: Color(0xFF2d2d2d)
                                            ),)),
                                            Expanded(
                                              child: Text(
                                                textAlign:TextAlign.right,
                                                "${running_balance.toString()}" ??
                                                    "-",style: TextStyle(
                                                color: Color(0xFF818181),
                                                fontSize: 13
                                              ),
                                              ),
                                            ),
                                          ],
                                        ),
                                        InkResponse(
                                          onTap: () async {
                                            Navigator.push(
                                              context,
                                              MaterialPageRoute(
                                                builder:
                                                    (context) => Transactiondetails(
                                                  paymentID: item.refId,
                                                      type: item.type,
                                                ),
                                              ),
                                            );
                                          },
                                          child: Container(
                                            padding: EdgeInsets.symmetric(vertical: 5),
                                            child: Row(
                                              crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                              mainAxisAlignment: MainAxisAlignment.start,
                                              children: [
                                                Text(
                                                  "View Details",
                                                  style: TextStyle(
                                                    fontFamily: "JakartaMedium",
                                                    fontSize: 14,
                                                    color: AppColors.app_blue,
                                                  ),
                                                ),
                                                SizedBox(width: 5),
                                                SvgPicture.asset(
                                                  "assets/svg/next_button.svg",
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                }).toList(),
                              ],
                            ),
                          );
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
          onWillPop: () {
            return _onBackPressed(context);
          },
        );
      },
    );
  }

  Future<bool> _onBackPressed(BuildContext context) async {
    Navigator.pop(context, true);
    return true;
  }
}
