import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Utils/GlobalConstants.dart';
import 'package:generp/screens/finance/paymentReceiptDetails.dart';
import 'package:provider/provider.dart';

import '../../Notifiers/financeProvider/paymentReceiptsProvider.dart';
import '../../Notifiers/financeProvider/paymentRequisitionPaymentsListProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonServices.dart';
import '../../Utils/commonWidgets.dart';
import '../commonDateRangeFilter.dart';

class Paymentreceiptlist extends StatefulWidget {
  final String pageTitleName;

  const Paymentreceiptlist({super.key, required this.pageTitleName});

  @override
  State<Paymentreceiptlist> createState() => _PaymentreceiptlistState();
}

class _PaymentreceiptlistState extends State<Paymentreceiptlist> {
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });

    WidgetsBinding.instance.addPostFrameCallback((_) {
      var provider = Provider.of<Paymentreceiptsprovider>(
        context,
        listen: false,
      );
      provider.resetPagination();
      provider.paymentsListAPI(context, '', '');

      _scrollController.addListener(() {
        if (_scrollController.position.pixels >=
            _scrollController.position.maxScrollExtent - 200) {
          provider.loadMore(context, '', '');
        }
      });
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _connectivity.disposeStream();
    super.dispose();
  }

  @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<Paymentreceiptsprovider>(
      builder: (context, provider, child) {
        final receipts = provider.receiptsList;
        final requestLists = provider.receiptsList;
        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: appbar2New(
            context,
            widget.pageTitleName,
            provider.resetForm,
            Row(
              children: [
                // InkResponse(
                //   onTap: () {
                //     _showOptionsSheet(context);
                //   },
                //   child: SvgPicture.asset("assets/svg/ic_download.svg",),
                // ),
                InkResponse(
                  onTap: () async {
                    HapticFeedback.selectionClick();
                    var cf = Commondaterangefilter();
                    var result = await cf.showFilterBottomSheet(context);
                    if (result != null) {
                      var dateRange = result['dateRange'] as DateTimeRange?;
                      print("dateRange: $dateRange");

                      var formatted = result['formatted'] as List<String>;
                      print("formatted: $formatted");

                      if (formatted.isNotEmpty) {
                        var fromDate = formatted[0]; // From date
                        var toDate = formatted[1]; // To date
                        print("from_date: $fromDate");
                        print("to_date: $toDate");
                        provider.paymentsListAPI(context, fromDate, toDate);
                        // You can now use fromDate and toDate as needed
                        // For example, store them or pass to another function
                      } else {
                        print("No valid date range selected");
                      }
                    } else {
                      print("Bottom sheet closed without selection");
                    }
                  },
                  child: SvgPicture.asset(
                    "assets/svg/filter_ic.svg",
                    height: 25,
                  ),
                ),
              ],
            ),
            0xFFFFFFFF,
          ),
          backgroundColor: AppColors.scaffold_bg_color,
          body:
              provider.isLoading
                  ? Center(
                    child: CircularProgressIndicator.adaptive(
                      valueColor: AlwaysStoppedAnimation<Color>(
                        AppColors.app_blue,
                      ),
                    ),
                  )
                  : receipts.isNotEmpty
                  ? Scrollbar(
                    controller: _scrollController,
                    child: ListView.builder(
                      controller: _scrollController,
                      itemCount:
                          receipts.length + (provider.hasMoreData ? 1 : 0),
                      itemBuilder: (context, index) {
                        if (index == receipts.length) {
                          return provider.isLoadingMore
                              ? const Padding(
                                padding: EdgeInsets.all(16),
                                child: Center(
                                  child: CircularProgressIndicator(),
                                ),
                              )
                              : const SizedBox.shrink();
                        }

                        final receipt = receipts[index];
                        return InkResponse(
                          onTap: () async {
                            HapticFeedback.selectionClick();
                            var res = await Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => Paymentreceiptdetails(
                                      pageName: widget.pageTitleName,
                                      paymentRequestId: requestLists[index].id,
                                    ),
                                settings: RouteSettings(
                                  name: "Paymentreceiptdetails",
                                ),
                              ),
                            );
                            if (routeSettingName == "Paymentreceiptdetails") {
                              debugPrint("prd");
                              provider.paymentsListAPI(context, '', '');
                            }
                            // if (res == true) {
                            //   provider.paymentsListAPI(context, '', '');
                            // }
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 10,
                            ),
                            margin: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 5,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Column(
                              children: [
                                Row(
                                  children: [
                                    Expanded(
                                      flex: 1,
                                      child: Container(
                                        height: 50,
                                        width: 50,
                                        padding: EdgeInsets.all(3.0),
                                        decoration: BoxDecoration(
                                          color: AppColors.requested_bg_color,
                                          shape: BoxShape.circle,
                                        ),
                                        child: SvgPicture.asset(
                                          "assets/svg/finance/rupee_ic.svg",
                                          fit: BoxFit.scaleDown,
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 10),
                                    Expanded(
                                      flex: 4,
                                      child: SizedBox(
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              requestLists[index]
                                                  .receipientAccount!,
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                fontFamily: "JakartaRegular",
                                                fontSize: 14,
                                                color: AppColors.semi_black,
                                              ),
                                            ),
                                            Text(
                                              "${requestLists[index].receiptDate}",
                                              style: TextStyle(
                                                fontFamily: "JakartaRegular",
                                                fontSize: 14,
                                                color: AppColors.grey_semi,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 10),
                                    Expanded(
                                      flex: 3,
                                      child: Text(
                                        "₹${requestLists[index].amount}",
                                        textAlign: TextAlign.right,
                                        maxLines: 1,
                                        style: TextStyle(
                                          fontFamily: "JakartaMedium",
                                          fontSize: 14,
                                          color: AppColors.app_blue,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  )
                  : Emptywidget(context),
        );
      },
    );
  }

  Future<void> _showOptionsSheet(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<Paymentrequisitionpaymentslistprovider>(
                builder: (context, provider, child) {
                  return Container(
                    margin: EdgeInsets.only(
                      bottom: 15,
                      left: 15,
                      right: 15,
                      top: 10,
                    ),
                    padding: EdgeInsets.only(
                      bottom: MediaQuery.of(context).viewInsets.bottom,
                    ),
                    child: SingleChildScrollView(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(height: 15),

                          ...List.generate(5, (index) {
                            final assetnames = [
                              "se_locate_customer",
                              "se_locate_customer",
                              "se_update_complaint",
                              "se_payment_details",
                              "se_payment_details",
                            ];
                            final Headingnames = [
                              "Copy to Clipboard",
                              "Download CSV",
                              "Download XLSX",
                              "Download PDF",
                              "Print Data",
                            ];
                            return ListTile(
                              onTap: () {
                                HapticFeedback.selectionClick();
                                switch (index) {
                                  case 0:
                                    provider.copyToClipboard(context);
                                    break;
                                  case 1:
                                    provider.downloadCSV(context);
                                    break;
                                  case 2:
                                    provider.downloadXLS(context);
                                    break;
                                  case 3:
                                    provider.downloadPDF(context);
                                    break;
                                  case 4:
                                    provider.printData(context);
                                    break;
                                }
                              },
                              leading: SvgPicture.asset(
                                "assets/svg/${assetnames[index]}.svg",
                              ),
                              title: Text(
                                Headingnames[index],
                                style: TextStyle(fontFamily: "JakartaMedium"),
                              ),
                              trailing: SvgPicture.asset(
                                "assets/svg/arrow_right_new.svg",
                              ),
                            );
                          }),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
