import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/PCWalletProvider.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:provider/provider.dart';

import '../../Models/PaymentCollectionWalletResponse.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonServices.dart';

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

  @override
  State<Pcwallet> createState() => _PcwalletState();
}

class _PcwalletState extends State<Pcwallet> {
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

  @override
  void initState() {
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      var provider = Provider.of<Pcwalletprovider>(context, listen: false);
      provider.LoadTransactionsListAPI(context);
    });
  }

  @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<Pcwalletprovider>(
      builder: (context, provider, child) {
        final groupedData = provider.groupByDate(provider.historyList);
        return WillPopScope(
          onWillPop: () => onBackPressed(context),
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS ? false : true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,

              ///Container(
              //                         padding: EdgeInsets.symmetric(horizontal: 10),
              //                         height: 40,
              //                         decoration: BoxDecoration(
              //                           color: Color(0xFFF2FAFF),
              //                           borderRadius: BorderRadius.circular(16),
              //                         ),
              //                         child: Row(
              //                           mainAxisAlignment: MainAxisAlignment.center,
              //                           children: [
              //                             SvgPicture.asset(
              //                               'assets/svg/pc_wallet.svg',
              //                               height: 30,
              //                             ),
              //                             SizedBox(width: 5),
              //                             Text(
              //                               "${provider.totlDetails.balanceAmount??"0.00"}",
              //                               style: TextStyle(fontSize: 14),
              //                             ),
              //                           ],
              //                         ),
              //                       ),
              appBar: appbarNew(context, "P.C. Wallet", 0xFFFFFFFF),
              backgroundColor: AppColors.scaffold_bg_color,
              body: Container(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      Container(
                        margin: EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 10,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(16),
                        ),
                        child: Column(
                          children: [
                            Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 10,
                                vertical: 15,
                              ),
                              margin: EdgeInsets.symmetric(
                                horizontal: 10,
                                vertical: 10,
                              ),
                              decoration: BoxDecoration(
                                color: Color(0xFFEDF7FF),
                                borderRadius: BorderRadius.circular(16),
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text(
                                        "₹${provider.totlDetails.balanceAmount ?? "-"}",
                                        style: TextStyle(
                                          fontSize: 20,
                                          fontFamily: "JakartaMedium",
                                          color: AppColors.app_blue,
                                        ),
                                      ),
                                    ],
                                  ),
                                  Container(
                                    padding: EdgeInsets.only(top: 5),
                                    child: Text(
                                      "Balance Amount",
                                      maxLines: 1,
                                      style: TextStyle(
                                        fontSize: 14,
                                        fontFamily: "JakartaRegular",
                                        color: AppColors.semi_black,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),

                            Row(
                              children: [
                                ...List.generate(2, (jj) {
                                  final texts = ["Credited", "Debited"];
                                  final heads = [
                                    provider.totlDetails.creditAmount ?? "-",
                                    provider.totlDetails.debitAmount ?? "-",
                                  ];
                                  final svgs = [
                                    "assets/svg/finance/cred_debit_ic.svg",
                                    "assets/svg/finance/deb_credit_ic.svg",
                                  ];
                                  return Expanded(
                                    child: Container(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 10,
                                        vertical: 10,
                                      ),
                                      margin: EdgeInsets.symmetric(
                                        horizontal: 10,
                                        vertical: 5,
                                      ),
                                      decoration: BoxDecoration(
                                        color:
                                            texts[jj] == "Debited"
                                                ? Color(0xFFFFEFEF)
                                                : Color(0xFFE7FFE5),
                                        borderRadius: BorderRadius.circular(16),
                                      ),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            "₹${heads[jj] ?? "-"}",
                                            maxLines: 2,
                                            style: TextStyle(
                                              fontSize: 20,
                                              color:
                                                  texts[jj] == "Debited"
                                                      ? Color(0xFFEF3739)
                                                      : Color(0xFF0D9C00),
                                              fontFamily: "JakartaMedium",
                                            ),
                                          ),
                                          Container(
                                            padding: EdgeInsets.only(top: 5),
                                            child: Row(
                                              children: [
                                                Expanded(
                                                  flex: 3,
                                                  child: Text(
                                                    texts[jj] ?? "-",
                                                    maxLines: 1,
                                                    style: TextStyle(
                                                      fontSize: 14,
                                                      fontFamily:
                                                          "JakartaRegular",
                                                      color:
                                                          AppColors.semi_black,
                                                    ),
                                                  ),
                                                ),
                                                Expanded(
                                                  flex: 1,
                                                  child: SvgPicture.asset(
                                                    svgs[jj],
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  );
                                }),
                              ],
                            ),
                            SizedBox(height: 5),
                          ],
                        ),
                      ),

                      ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemCount: provider.historyList.length,
                        itemBuilder: (context, index) {
                          double runningBalance = 0;
                          int currentIndex = provider.historyList.indexOf(
                            provider.historyList[index],
                          );

                          String part1 =
                              provider.historyList[index].description!
                                  .split(' (')
                                  .first;

                          RegExp regExp = RegExp(r'\(([^)]+)\)');
                          String? part2 = regExp
                              .firstMatch(
                                provider.historyList[index].description!,
                              )
                              ?.group(1);

                          return Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 10,
                            ),
                            margin: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 5,
                            ),
                            // margin: EdgeInsets.symmetric(vertical: 5),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Expanded(
                                  flex: 1,
                                  child: SizedBox(
                                    child:
                                        provider
                                                    .historyList[index]
                                                    .transactionType ==
                                                "Debit"
                                            ? SvgPicture.asset(
                                              "assets/svg/finance/debited_filled_ic.svg",
                                              height: 45,
                                              width: 45,
                                              fit: BoxFit.contain,
                                            )
                                            : SvgPicture.asset(
                                              "assets/svg/finance/credited_filled_ic.svg",
                                              height: 45,
                                              width: 45,
                                              fit: BoxFit.contain,
                                            ),
                                  ),
                                ),
                                SizedBox(width: 10),
                                Expanded(
                                  flex: 8,
                                  child: SizedBox(
                                    child: Column(
                                      children: [
                                        Row(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            // Expanded(
                                            //   flex: 5,
                                            //   child: SizedBox(
                                            //     child: Text(
                                            //       provider
                                            //           .historyList[index]
                                            //           .description ??
                                            //           "-",
                                            //       maxLines: 2,
                                            //       overflow: TextOverflow.ellipsis,
                                            //       style: TextStyle(
                                            //         fontFamily: "JakartaRegular",
                                            //         fontSize: 14,
                                            //       ),
                                            //     ),
                                            //   ),
                                            // ),
                                            Expanded(
                                              flex: 5,
                                              child: SizedBox(
                                                child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: [
                                                    Text(
                                                      part1,
                                                      maxLines: 2,
                                                      style: TextStyle(
                                                        fontFamily:
                                                            "JakartaMedium",
                                                        fontSize: 14,
                                                      ),
                                                    ),
                                                    if (part2 != null)
                                                      Text(
                                                        part2,
                                                        maxLines: 2,
                                                        style: TextStyle(
                                                          color:
                                                              AppColors
                                                                  .grey_semi,
                                                          fontSize: 14,
                                                        ),
                                                      ),
                                                  ],
                                                ),
                                              ),
                                            ),
                                            Spacer(),
                                            Expanded(
                                              flex: 3,
                                              child: SizedBox(
                                                child: RichText(
                                                  maxLines: 1,
                                                  textAlign: TextAlign.right,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  text: TextSpan(
                                                    children: [
                                                      TextSpan(
                                                        text:
                                                            provider
                                                                        .historyList[index]
                                                                        .transactionType ==
                                                                    "Debit"
                                                                ? "-"
                                                                : "+",
                                                        style: TextStyle(
                                                          color:
                                                              provider
                                                                          .historyList[index]
                                                                          .transactionType ==
                                                                      "Debit"
                                                                  ? Color(
                                                                    0xFFEF3739,
                                                                  )
                                                                  : Color(
                                                                    0xFF0D9C00,
                                                                  ),
                                                          fontSize: 14,
                                                          fontFamily:
                                                              "JakartaRegular",
                                                        ),
                                                      ),
                                                      TextSpan(
                                                        text:
                                                            "₹${provider.historyList[index].transactionType == "Debit" ? "${provider.historyList[index].amount}" : "${provider.historyList[index].amount}"}",
                                                        style: TextStyle(
                                                          color:
                                                              provider
                                                                          .historyList[index]
                                                                          .transactionType ==
                                                                      "Debit"
                                                                  ? Color(
                                                                    0xFFEF3739,
                                                                  )
                                                                  : Color(
                                                                    0xFF0D9C00,
                                                                  ),
                                                          fontSize: 14,
                                                          fontFamily:
                                                              "JakartaRegular",
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                        SizedBox(height: 7),
                                        Row(
                                          children: [
                                            Expanded(
                                              flex: 5,
                                              child: SizedBox(
                                                child: Text(
                                                  provider
                                                          .historyList[index]
                                                          .datetime ??
                                                      "-",
                                                  maxLines: 2,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style: TextStyle(
                                                    fontFamily:
                                                        "JakartaRegular",
                                                    color: AppColors.grey_semi,
                                                    fontSize: 12,
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _scaffold1(BuildContext context) {
    return Consumer<Pcwalletprovider>(
      builder: (context, provider, child) {
        final groupedData = provider.groupByDate(provider.historyList);
        return WillPopScope(
          onWillPop: () => onBackPressed(context),
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS ? false : true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,

              ///Container(
              //                         padding: EdgeInsets.symmetric(horizontal: 10),
              //                         height: 40,
              //                         decoration: BoxDecoration(
              //                           color: Color(0xFFF2FAFF),
              //                           borderRadius: BorderRadius.circular(16),
              //                         ),
              //                         child: Row(
              //                           mainAxisAlignment: MainAxisAlignment.center,
              //                           children: [
              //                             SvgPicture.asset(
              //                               'assets/svg/pc_wallet.svg',
              //                               height: 30,
              //                             ),
              //                             SizedBox(width: 5),
              //                             Text(
              //                               "${provider.totlDetails.balanceAmount??"0.00"}",
              //                               style: TextStyle(fontSize: 14),
              //                             ),
              //                           ],
              //                         ),
              //                       ),
              appBar: appbarNew(context, "P.C. Wallet", 0xFFFFFFFF),
              backgroundColor: AppColors.scaffold_bg_color,
              body: Container(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 15,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(16),
                        ),
                        child: Row(
                          children: [
                            Expanded(
                              child: Container(
                                padding: EdgeInsets.symmetric(
                                  horizontal: 15,
                                  vertical: 15,
                                ),
                                decoration: BoxDecoration(
                                  color: Color(0xFFE7FFE5),
                                  borderRadius: BorderRadius.circular(16),
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        Text(
                                          "₹",
                                          style: TextStyle(
                                            height: 1,
                                            color: Color(0xFF0D9C00),
                                          ),
                                        ),
                                        Text(
                                          provider.totlDetails.creditAmount ??
                                              "0.00",
                                          style: TextStyle(
                                            fontSize: 30,
                                            height: 1,
                                            color: Color(0xFF0D9C00),
                                          ),
                                        ),
                                      ],
                                    ),
                                    Text(
                                      "Credited",
                                      style: TextStyle(
                                        fontFamily: "JakartaMedium",
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            SizedBox(width: 10),
                            Expanded(
                              child: Container(
                                padding: EdgeInsets.symmetric(
                                  horizontal: 15,
                                  vertical: 15,
                                ),
                                decoration: BoxDecoration(
                                  color: Color(0xFFFFEFEF),
                                  borderRadius: BorderRadius.circular(16),
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        Text(
                                          "₹",
                                          style: TextStyle(
                                            height: 1,
                                            color: Color(0xFFED3424),
                                          ),
                                        ),
                                        Text(
                                          "${provider.totlDetails.debitAmount ?? 0.00}",
                                          style: TextStyle(
                                            fontSize: 30,
                                            height: 1,
                                            color: Color(0xFFED3424),
                                          ),
                                        ),
                                      ],
                                    ),
                                    Text(
                                      "Debited",
                                      style: TextStyle(
                                        fontFamily: "JakartaMedium",
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemCount: groupedData.keys.length,
                        itemBuilder: (context, index) {
                          String date = groupedData.keys.elementAt(index);
                          List<HistoryList> 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) {
                                  String part1 =
                                      item.description!.split(' (').first;

                                  RegExp regExp = RegExp(r'\(([^)]+)\)');
                                  String? part2 = regExp
                                      .firstMatch(item.description!)
                                      ?.group(1);

                                  return Container(
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 10,
                                      vertical: 10,
                                    ),
                                    decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.circular(16),
                                    ),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: [
                                        Expanded(
                                          flex: 1,
                                          child: SizedBox(
                                            child:
                                                item.transactionType == "Credit"
                                                    ? Image.asset(
                                                      "assets/images/trans_credit.png",
                                                      height: 45,
                                                      width: 45,
                                                      fit: BoxFit.contain,
                                                    )
                                                    : Image.asset(
                                                      "assets/images/trans_debit.png",
                                                      height: 45,
                                                      width: 45,
                                                      fit: BoxFit.contain,
                                                    ),
                                          ),
                                        ),
                                        SizedBox(width: 10),
                                        Expanded(
                                          flex: 5,
                                          child: SizedBox(
                                            child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Text(
                                                  part1,
                                                  style: TextStyle(
                                                    fontFamily: "JakartaMedium",
                                                  ),
                                                ),
                                                Text(
                                                  "$part2",
                                                  style: TextStyle(
                                                    color: Color(0xFF818181),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                        Spacer(),
                                        Expanded(
                                          flex: 2,
                                          child: SizedBox(
                                            child: RichText(
                                              text: TextSpan(
                                                children: [
                                                  TextSpan(
                                                    text:
                                                        item.transactionType ==
                                                                "Credit"
                                                            ? "+"
                                                            : "-",
                                                    style: TextStyle(
                                                      color: Color(0xFF2D2D2D),
                                                      fontSize: 14,
                                                      fontFamily:
                                                          "JakartaRegular",
                                                    ),
                                                  ),
                                                  TextSpan(
                                                    text: "₹${item.amount!}",
                                                    style: TextStyle(
                                                      color: Color(0xFF2D2D2D),
                                                      fontSize: 14,
                                                      fontFamily:
                                                          "JakartaMedium",
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                }),
                              ],
                            ),
                          );
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
