import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/commonProvider/accountLedgerProvider.dart';
import 'package:generp/screens/commom/transactionDetails.dart';
import 'package:provider/provider.dart';

import '../../Models/commonModels/commonAccountLedgerFilterResponse.dart';
import '../../Models/commonModels/commonAccountLedgerResponse.dart';
import '../../Notifiers/commonProvider/accountDetailsProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';
import '../../Utils/dropdownTheme.dart';

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

  @override
  State<Accountledger> createState() => _AccountledgerState();
}

class _AccountledgerState extends State<Accountledger> {
  Dropdowntheme ddtheme = Dropdowntheme();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var provider = Provider.of<Accountledgerprovider>(context, listen: false);
      provider.dropDownAPI(context);
      provider.ledgerlistAPI(context);
      _showFilterSheet(context);
    });
  }
  Future<bool> _onBackPressed(BuildContext context) async {
    Provider.of<Accountledgerprovider>(context, listen: false).resetAll();
    Navigator.pop(context, true);
    return true;
  }
  @override
  Widget build(BuildContext context) {
    return Consumer<Accountledgerprovider>(
      builder: (context, provider, child) {
        final groupedData = provider.groupByDate(provider.ledgerList);

        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(
            resizeToAvoidBottomInset: true,
            appBar: appbar2(
              context,
              "Account Ledger List",
              provider.resetAll,
              Row(
                children: [
                  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,
                        ),)
                      ],
                    ),
                  ),SizedBox(width: 10,),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 5, vertical: 5),

                    child: InkResponse(
                      onTap: () {
                        _showFilterSheet(context);
                      },
                      child: SvgPicture.asset("assets/svg/filter_ic.svg", height: 25),
                    ),
                  ),
                ],
              ),
            ),
            backgroundColor: AppColors.scaffold_bg_color,
            body:  SafeArea(child: provider.isLoading
                ? Center(child: CircularProgressIndicator.adaptive(
                valueColor: AlwaysStoppedAnimation<Color>(
                    AppColors.app_blue)
            )):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)),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text("${provider.selectedAcVal??""}" +" "+ "Account Ledger List"),
                    ),
                    if(provider.ledgerList.isEmpty)...[
                      Emptywidget(context),
                    ]else...[
                      ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemCount: groupedData.keys.length,
                        itemBuilder: (context, index) {
                          String date = groupedData.keys.elementAt(index);
                          List<LedgerList> items = groupedData[date]!;
                          if (provider.ledgerList.isEmpty) {
                            return Center(child: Text("No Data Available"));
                          }
                          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(
                                                  textAlign: TextAlign.right,
                                                  maxLines: 1,
                                                  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<void> _showFilterSheet(BuildContext context) {
    return showModalBottomSheet(
      useSafeArea: true,
      isDismissible: true,
      isScrollControlled: true,
      showDragHandle: true,
      backgroundColor: Colors.white,
      enableDrag: true,
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return SafeArea(
              child: Consumer<Accountledgerprovider>(
                builder: (context, provider, child) {
                  return Container(
                    padding: EdgeInsets.only(
                      bottom: MediaQuery.of(context).viewInsets.bottom,
                    ),
                    margin: EdgeInsets.only(
                      bottom: 15,
                      left: 15,
                      right: 15,
                      top: 10,
                    ),

                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Padding(
                            padding: EdgeInsets.symmetric(vertical: 10),
                            child: Text(
                              "Filter",
                              style: TextStyle(
                                color: AppColors.app_blue,
                                fontSize: 16,
                                fontFamily: "JakartaMedium",
                              ),
                            ),
                          ),

                          Text(
                            "Select Account",
                            style: TextStyle(color: Color(0xFF2D2D2D)),
                          ),
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<Accounts>(
                                    isExpanded: true,
                                    hint: Text(
                                      'Select Account Type',
                                      style: TextStyle(fontSize: 14),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    items:
                                        provider.accounts
                                            .map(
                                              (accs) =>
                                                  DropdownMenuItem<Accounts>(
                                                    value: accs,
                                                    child: Text(
                                                      accs.name ?? '',
                                                      style: const TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                    ),
                                                  ),
                                            )
                                            .toList(),
                                    value:provider.accounts.contains(provider.selectedAccount)?provider.selectedAccount:null,
                                    // value: provider.selectedAccount,
                                    onChanged: (Accounts? value) {
                                      if (value != null) {
                                        if (provider.accounts.isNotEmpty) {
                                          provider.selectedAccount = value;
                                          print(
                                            "Selected Complaint Type: ${value.name}, ID: ${value.id}",
                                          );
                                          provider.selectedAcId = value.id!;
                                          provider.selectedAcVal = value.name!;
                                          print(
                                            "hfjkshfg" +
                                                provider.selectedAcId
                                                    .toString(),
                                          );
                                          Navigator.pop(context);
                                          provider.ledgerlistAPI(context);
                                        }
                                      }
                                    },
                                    dropdownSearchData: DropdownSearchData(
                                      searchInnerWidgetHeight: 50,
                                      searchController:
                                      provider
                                          .searchAccountController,
                                      searchInnerWidget: Padding(
                                        padding: const EdgeInsets.all(8),
                                        child: TextFormField(
                                          controller:
                                          provider
                                              .searchAccountController,
                                          decoration: InputDecoration(
                                            isDense: true,
                                            contentPadding:
                                            const EdgeInsets.symmetric(
                                              horizontal: 10,
                                              vertical: 8,
                                            ),
                                            hintText: 'Search account...',
                                            border: OutlineInputBorder(
                                              borderRadius:
                                              BorderRadius.circular(8),
                                            ),
                                          ),
                                        ),
                                      ),
                                      searchMatchFn: (item, searchValue) {
                                        return item.value?.name
                                            ?.toLowerCase()
                                            .contains(
                                          searchValue.toLowerCase(),
                                        ) ??
                                            false;
                                      },

                                      // Optional: clear search text when dropdown closes
                                    ),
                                    onMenuStateChange: (isOpen) {
                                      if (!isOpen) {
                                        provider.searchAccountController
                                            .clear();
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData: ddtheme.menuItemStyleData,
                                    dropdownStyleData: ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
