import 'dart:io';

import 'package:auto_size_text/auto_size_text.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
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/Utils/commonServices.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();
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
    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
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _connectivity.disposeStream();
  }

  @override
  Widget build(BuildContext context) {
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.mobile:
        connection = 'Online';
        break;
      case ConnectivityResult.wifi:
        connection = 'Online';
        break;
      case ConnectivityResult.none:
      default:
        connection = 'Offline';
    }
    return (connection == "Online")
        ? Platform.isAndroid
            ? WillPopScope(
              onWillPop: () => onBackPressed(context),
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(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;
        var headings = [
          "Name",
          "Address",
          "Account Holder Name",
          "Account Number",
        ];
        var headings2 = [
          "Bank Name",
          "Bank Branch Name",
          "Bank IFSC Code",
          "Bank UPI ID",
          "State",
          "District",
          "Sub Locality",
        ];

        var values = [
          provider.acDetails.name,
          provider.acDetails.address,
          provider.acDetails.bankAccountHolderName,
          provider.acDetails.bankAccountNumber,
        ];

        var values2 = [
          provider.acDetails.bankName,
          provider.acDetails.bankBranchName,
          provider.acDetails.bankIfscCode,
          provider.acDetails.bankUpiId,
          provider.acDetails.state,
          provider.acDetails.district,
          provider.acDetails.subLocality,
        ];

        var totalHeadings = [...headings];
        var totalValues = [...values];

        if (provider.showMoreDetails) {
          totalHeadings = [...headings, ...headings2];
          totalValues = [...values, ...values2];
        }
        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: appbar2New(
            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(
                        provider.balanceDetails.balance.toString() ?? "-",
                        style: TextStyle(fontSize: 12),
                      ),
                    ],
                  ),
                ),
                SizedBox(width: 10),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 5, vertical: 5),

                  child: GestureDetector(
                    onTap: () {
                      print("Tapped");

                      _showFilterSheet(context);
                    },
                    child: SvgPicture.asset(
                      "assets/svg/search_ic.svg",
                      height: 25,
                    ),
                  ),
                ),
              ],
            ),
            0xFFFFFFFF
          ),
          backgroundColor: AppColors.scaffold_bg_color,
          body:
              provider.isLoading
                  ? Center(
                    child: CircularProgressIndicator.adaptive(
                      valueColor: AlwaysStoppedAnimation<Color>(
                        AppColors.app_blue,
                      ),
                    ),
                  )
                  : SizedBox(
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              "${provider.selectedAcVal ?? ""}" +
                                  " " +
                                  "Account Ledger List",
                            ),
                          ),
                          if (provider.ledgerList.isEmpty) ...[
                            Emptywidget(context),
                          ] else ...[
                            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: [
                                          AutoSizeText(
                                            "${provider.balanceDetails.totalCredit}",
                                            style: TextStyle(
                                              color: Color(0xFFED3424),
                                              fontFamily: "JakartaRegular",
                                              fontSize: 25,
                                            ),
                                            maxLines: 2,
                                            minFontSize: 18,
                                            maxFontSize: 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: [
                                          AutoSizeText(
                                            "${provider.balanceDetails.totalDebit}",
                                            style: TextStyle(
                                              color: Color(0xFFED3424),
                                              fontFamily: "JakartaRegular",
                                              fontSize: 25,
                                            ),
                                            minFontSize: 18,
                                            maxFontSize: 25,
                                            maxLines: 2,
                                          ),
                                          Text(
                                            "debit",
                                            style: TextStyle(
                                              color: Color(0xFF818181),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),

                            Container(
                              alignment: Alignment.topLeft,
                              padding: EdgeInsets.symmetric(
                                horizontal: 10,
                                vertical: 10,
                              ),
                              child: Text(
                                "Account Details",
                                style: TextStyle(
                                  fontFamily: "JakartaMedium",
                                  color: Color(0xFF818181),
                                ),
                              ),
                            ),
                            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(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  ...List.generate(totalHeadings.length, (
                                    index,
                                  ) {
                                    return Container(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 10,
                                        vertical: 5,
                                      ),
                                      child: Row(
                                        // crossAxisAlignment: CrossAxisAlignment.start,
                                        // mainAxisAlignment: MainAxisAlignment.start,
                                        children: [
                                          Expanded(
                                            child: Text(
                                              totalHeadings[index],
                                              style: TextStyle(
                                                fontFamily: "JakartaMedium",
                                              ),
                                            ),
                                          ),

                                          Expanded(
                                            child: Text(
                                              "${totalValues[index]}",

                                              style: TextStyle(
                                                color: Color(0xFF818181),
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    );
                                  }),
                                  InkResponse(
                                    onTap: () async {
                                      provider.showMoreDetails =
                                          !provider.showMoreDetails;
                                    },
                                    child: Container(
                                      padding: EdgeInsets.symmetric(
                                        vertical: 5,
                                      ),
                                      child: Row(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Text(
                                            provider.showMoreDetails
                                                ? "- Show Less"
                                                : "+ More Details",
                                            style: TextStyle(
                                              fontFamily: "JakartaMedium",
                                              fontSize: 14,
                                              color: AppColors.app_blue,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            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 runningBalance = 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;
                                          runningBalance += (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,
                                                                description: item.description,
                                                              ),
                                                      settings: RouteSettings(
                                                        name:
                                                            "Transactiondetails",
                                                      ),
                                                    ),
                                                  );
                                                },
                                                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",
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                        );
                                      }),
                                    ],
                                  ),
                                );
                              },
                            ),
                          ],
                        ],
                      ),
                    ),
                  ),
        );
      },
    );
  }

  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(
                    height: MediaQuery.of(context).size.height * 0.35,
                    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}",
                                          );

                                          provider.ledgerlistAPI(context);
                                          Navigator.pop(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,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
