import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Utils/GlobalConstants.dart';
import 'package:generp/screens/finance/FileViewer.dart';
import 'package:generp/screens/finance/paymentDetailsPaymentRequisition.dart';
import 'package:provider/provider.dart';
import '../../Notifiers/financeProvider/paymentRequisitionPaymentsListProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonServices.dart';
import '../../Utils/commonWidgets.dart';
import '../commonDateRangeFilter.dart';

class PaymentlistpaymentrequisitionOld extends StatefulWidget {
  final String pageTitleName;

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

  @override
  State<PaymentlistpaymentrequisitionOld> createState() =>
      _PaymentlistpaymentrequisitionOldState();
}

class _PaymentlistpaymentrequisitionOldState
    extends State<PaymentlistpaymentrequisitionOld> {
  late Commondaterangefilter cf;

  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) {
      cf = Commondaterangefilter();
      var provider = Provider.of<Paymentrequisitionpaymentslistprovider>(
        context,
        listen: false,
      );
      final now = DateTime.now();
      final range = DateTimeRange(
        start: DateTime(now.year, now.month, now.day),
        end: DateTime(now.year, now.month, now.day),
      );
      final dateRange = cf.getFormattedDateRange(range);
      provider.paymentsListAPI(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<Paymentrequisitionpaymentslistprovider>(
      builder: (context, provider, child) {
        final requestLists = provider.paymentsList;
        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: appbar2(
            context,
            widget.pageTitleName,
            provider.resetForm,
            Row(
              children: [
                // InkResponse(
                //   onTap: () {
                //     _showOptionsSheet(context);
                //   },
                //   child: SvgPicture.asset("assets/svg/ic_download.svg",),
                // ),
                InkResponse(
                  onTap: () async {
                    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,
                  ),
                ),
              ],
            ),
          ),
          backgroundColor: AppColors.scaffold_bg_color,
          body:
          provider.isLoading
              ? Center(
            child: CircularProgressIndicator.adaptive(
              valueColor: AlwaysStoppedAnimation<Color>(
                AppColors.app_blue,
              ),
            ),
          )
              : requestLists.isNotEmpty
              ? SizedBox(
            child: Scrollbar(
              thumbVisibility: false,

              child: ListView.builder(
                itemCount: requestLists.length,
                shrinkWrap: true,
                physics: AlwaysScrollableScrollPhysics(),
                itemBuilder: (context, index) {
                  return Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 10,
                      vertical: 10,
                    ),
                    margin: EdgeInsets.symmetric(
                      horizontal: 10,
                      vertical: 10,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Column(
                      children: [
                        Row(
                          children: [
                            Expanded(
                              flex: 1,
                              child: Container(
                                height: 50,
                                width: 35,
                                padding: EdgeInsets.all(8.0),
                                decoration: BoxDecoration(
                                  color: Color(0xFFFFF3CE),
                                  borderRadius: BorderRadius.circular(
                                    8,
                                  ),
                                ),
                                child: SvgPicture.asset(
                                  "assets/svg/fin_ic.svg",
                                ),
                              ),
                            ),
                            SizedBox(width: 10),
                            Expanded(
                              flex: 4,
                              child: SizedBox(
                                child: Column(
                                  crossAxisAlignment:
                                  CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      requestLists[index]
                                          .receipientAccount!,
                                      style: TextStyle(
                                        fontFamily: "JakartaMedium",
                                        fontSize: 14,
                                        color: AppColors.semi_black,
                                      ),
                                    ),
                                    Text(
                                      "₹${requestLists[index].amount}",
                                      style: TextStyle(
                                        fontFamily: "JakartaMedium",
                                        fontSize: 14,
                                        color: AppColors.app_blue,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            // Expanded(
                            //   flex: 2,
                            //   child: Container(
                            //     padding: EdgeInsets.symmetric(
                            //       horizontal: 5,
                            //       vertical: 10,
                            //     ),
                            //     decoration: BoxDecoration(
                            //       borderRadius: BorderRadius.circular(8),
                            //       color: Color(0xFFE3FFE0),
                            //     ),
                            //     child: Center(
                            //       child: Text(
                            //         requestLists[index].refType!,
                            //         textAlign: TextAlign.center,
                            //         style: TextStyle(
                            //           fontFamily: "JakartaMedium",
                            //           fontSize: 14,
                            //           color: Color(0xFF0D9C00),
                            //         ),
                            //       ),
                            //     ),
                            //   ),
                            // ),
                          ],
                        ),
                        Divider(
                          thickness: 0.5,
                          color: Color(0xFFD7D7D7),
                        ),
                        ...List.generate(5, (j) {
                          final headings = [
                            "To Account",
                            "Attachment",
                            "Request Mode",

                            "Payment Date",
                            "Note",
                          ];

                          final subHeadings = [
                            requestLists[index].payAccount,
                            "View",
                            requestLists[index].requestMode,

                            // requestLists[index].attachmentDirFilePath
                            requestLists[index].paymentDate,
                            requestLists[index].description,
                          ];
                          if (headings[j] == "Attachment" &&
                              requestLists[index]
                                  .attachmentViewFileName ==
                                  "") {
                            return SizedBox.shrink();
                          }
                          return Container(
                            padding: EdgeInsets.symmetric(vertical: 5),
                            child: Row(
                              crossAxisAlignment:
                              CrossAxisAlignment.start,
                              children: [
                                Expanded(
                                  child: Text(
                                    headings[j],
                                    style: TextStyle(
                                      fontFamily: "JakartaMedium",
                                      fontSize: 14,
                                      color: AppColors.semi_black,
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: InkResponse(
                                    onTap:
                                    j != 1
                                        ? null
                                        : () {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder:
                                              (
                                              context,
                                              ) => Fileviewer(
                                            fileName:
                                            requestLists[index]
                                                .attachmentViewFileName!,
                                            fileUrl:
                                            requestLists[index]
                                                .attachmentDirFilePath!,
                                          ),
                                        ),
                                      );
                                    },
                                    child: Text(
                                      subHeadings[j] == ""
                                          ? "-"
                                          : subHeadings[j] ?? "-",
                                      style: TextStyle(
                                        fontSize: 14,
                                        color:
                                        j == 1
                                            ? AppColors.app_blue
                                            : Color(0xFF818181),
                                        decoration:
                                        j == 1
                                            ? TextDecoration
                                            .underline
                                            : TextDecoration.none,
                                        decorationColor:
                                        j == 1
                                            ? AppColors.app_blue
                                            : AppColors.white,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          );
                        }),
                        InkResponse(
                          onTap: () async {
                            var res = await Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) =>
                                    Paymentdetailspaymentrequisition(
                                      pageName:
                                      widget.pageTitleName,
                                      paymentRequestId:
                                      requestLists[index].id,
                                    ),
                                settings: RouteSettings(
                                  name:
                                  "Paymentdetailspaymentrequisition",
                                ),
                              ),
                            );
                            if (routeSettingName ==
                                "Paymentdetailspaymentrequisition") {
                              print("pld");

                              provider.paymentsListAPI(context, '', '');
                            }
                          },
                          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",
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          )
              : 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: () {
                                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",
                              ),
                            );
                          }),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
