import 'dart:io';

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

import '../../Utils/commonServices.dart';
import '../commonDateRangeFilter.dart';
import 'PaymentRequestionListDetails.dart';

class Allpaymentrequesitionlistsbymodes extends StatefulWidget {
  final String mode;
  final String pageTitleName;

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

  @override
  State<Allpaymentrequesitionlistsbymodes> createState() =>
      _AllpaymentrequesitionlistsbymodesState();
}

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

  late Commondaterangefilter cf;
  @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<Requestionlistprovider>(
        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);
      // print(dateRange);
      provider.paymentRequestionListsAPIFunction(context, widget.mode, "", "");
    });
  }

  @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: () {
                return onBackPressed(context);
              },
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(BuildContext context) {
    return Consumer<Requestionlistprovider>(
      builder: (context, provider, child) {
        final requestLists = provider.requisitionList;
        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.paymentRequestionListsAPIFunction(
                          context,
                          widget.mode,
                          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) {
                          if (requestLists.isEmpty) {
                            return SizedBox(
                              child: Center(child: Text("No Data Available")),
                            );
                          }
                          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].accountName!,
                                              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].status!,
                                            textAlign: TextAlign.center,
                                            style: TextStyle(
                                              fontFamily: "JakartaMedium",
                                              fontSize: 14,
                                              color: Color(0xFF0D9C00),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                Divider(
                                  thickness: 0.5,
                                  color: Color(0xFFD7D7D7),
                                ),
                                ...List.generate(4, (j) {
                                  final headings = [
                                    "Requesting Propose",
                                    "Attachment",
                                    "Requested Date",
                                    "Note",
                                  ];

                                  final subHeadings = [
                                    requestLists[index].requestingPurpose,
                                    "View",
                                    // requestLists[index].attachmentDirFilePath
                                    requestLists[index].date,
                                    requestLists[index].description,
                                  ];
                                  if (j == 1 &&
                                      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]!,
                                              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) =>
                                                Paymentrequestionlistdetails(
                                                  pageName:
                                                      widget.pageTitleName,
                                                  mode: widget.mode,
                                                  paymentRequestId:
                                                      requestLists[index].id,
                                                ),
                                        settings: RouteSettings(
                                          name: "Paymentrequestionlistdetails",
                                        ),
                                      ),
                                    );
                                    if (routeSettingName ==
                                        "Paymentrequestionlistdetails") {
                                      print("croos refresh");
                                      provider
                                          .paymentRequestionListsAPIFunction(
                                            context,
                                            widget.mode,
                                            "",
                                            "",
                                          );
                                    }
                                    // if (res == true) {
                                    //   print("android refresh");
                                    //   provider
                                    //       .paymentRequestionListsAPIFunction(
                                    //         context,
                                    //         widget.mode,
                                    //         "",
                                    //         "",
                                    //       );
                                    // }
                                    // if (Platform.isIOS) {
                                    //   print("IOS Refresh");
                                    //   if (didPushed == "true" ||
                                    //       didPopped == "true") {
                                    //     provider
                                    //         .paymentRequestionListsAPIFunction(
                                    //           context,
                                    //           widget.mode,
                                    //           "",
                                    //           "",
                                    //         );
                                    //   }
                                    // }
                                  },
                                  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<Requestionlistprovider>(
                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",
                              ),
                            );
                          }),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
