import 'dart:io';

import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/ordersProvider/paymentsProvider.dart';
import 'package:generp/screens/order/paymentDetailsByMode.dart';
import 'package:provider/provider.dart';

import '../../Models/ordersModels/paymentListByModeFilterResponse.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';
import '../../Utils/dropdownTheme.dart';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:generp/Utils/commonServices.dart';

class Paymentlistsbymode extends StatefulWidget {
  final mode;
  final pageTitleName;

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

  @override
  State<Paymentlistsbymode> createState() => _PaymentlistsbymodeState();
}

class _PaymentlistsbymodeState extends State<Paymentlistsbymode> {
  Dropdowntheme ddtheme = Dropdowntheme();
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;
  Color getDecorationColor(value) {
    var color = AppColors.approved_bg_color;
    switch (value) {
      case 'Registered':
        return AppColors.requested_bg_color;
      case 'Level 1 Approved':
        return AppColors.approved_bg_color;
      case 'Level 1 Rejected':
        return AppColors.rejected_bg_color;
      case 'Level 2 Approved':
        return AppColors.approved_bg_color;
      case 'Level 2 Rejected':
        return AppColors.rejected_bg_color;
      case 'Sales Order Registered':
        return AppColors.processed_bg_color;
      case 'Dispatched':
        return AppColors.approved_bg_color;
    }
    return color;
  }

  Color getTextColor(value) {
    var color = AppColors.approved_text_color;
    switch (value) {
      case 'Registered':
        return AppColors.requested_text_color;
      case 'Level 1 Approved':
        return AppColors.approved_text_color;
      case 'Level 1 Rejected':
        return AppColors.rejected_text_color;
      case 'Level 2 Approved':
        return AppColors.approved_text_color;
      case 'Level 2 Rejected':
        return AppColors.rejected_text_color;
      case 'Sales Order Registered':
        return AppColors.processed_text_color;
      case 'Dispatched':
        return AppColors.approved_text_color;
    }
    return color;
  }

  getText(value) {
    var text = "R";
    switch (value) {
      case 'Registered':
        return "R";
      case 'Level 1 Approved':
        return "L1A";
      case 'Level 1 Rejected':
        return "L1R";
      case 'Level 2 Approved':
        return "L2A";
      case 'Level 2 Rejected':
        return "L2R";
      case 'Sales Order Registered':
        return "SOR";
      case 'Dispatched':
        return "D";
    }
    return text;
  }

  //All","Registered","Level 1 Approved","Level 2 Approved","Level 1 Rejected",
  // Level 2 Rejected","Level 2 Rejected Final","Sales Order Registered","Dispatched"

  double getSize(value) {
    var text = "A";
    switch (value) {
      case 'Registered':
        return 16.0;
      case 'Level 1 Approved':
        return 13.0;
      case 'Level 1 Rejected':
        return 13.0;
      case 'Level 2 Approved':
        return 13.0;
      case 'Level 2 Rejected':
        return 13.0;
      case 'Processed':
        return 16.0;
      case 'Sales Order Registered':
        return 13.0;
      case 'Dispatched':
        return 16.0;
    }
    return 18.0;
  }

  final ScrollController _scrollController = ScrollController();

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

    WidgetsBinding.instance.addPostFrameCallback((_) {
      final provider = Provider.of<Paymentsprovider>(context, listen: false);
      provider.resetPagination();
      provider.paymentsListsByModeFilterAPIFunction(context, widget.mode);
      provider.paymentsListsByModeAPIFunction(context, widget.mode, "");
    });

    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
          _scrollController.position.maxScrollExtent - 200) {
        final provider = Provider.of<Paymentsprovider>(context, listen: false);
        provider.loadMore(context, widget.mode, "");
      }
    });
  }

  @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: () async {
                Provider.of<Paymentsprovider>(
                  context,
                  listen: false,
                ).resetAll();
                Navigator.pop(context, true);
                return true;
              },
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(BuildContext context) {
    return Consumer<Paymentsprovider>(
      builder: (context, provider, child) {
        final paymentLists = provider.paymentsList;
        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: appbar2New(
            context,
            widget.pageTitleName,
            provider.resetAll,
            Row(
              children: [
                // InkResponse(
                //   onTap: () {
                //     _showOptionsSheet(context);
                //   },
                //   child: SvgPicture.asset("assets/svg/ic_download.svg",),
                // ),
                InkResponse(
                  onTap: () async {
                    _showFilterSheet(context);
                  },
                  child: SvgPicture.asset(
                    "assets/svg/filter_ic.svg",
                    height: 25,
                  ),
                ),
              ],
            ),
            0xFFFFFFFF,
          ),
          backgroundColor: AppColors.scaffold_bg_color,
          body:
              provider.isLoading && paymentLists.isEmpty
                  ? Center(
                    child: CircularProgressIndicator.adaptive(
                      valueColor: AlwaysStoppedAnimation<Color>(
                        AppColors.app_blue,
                      ),
                    ),
                  )
                  : paymentLists.isNotEmpty
                  ? RefreshIndicator(
                    onRefresh: () async {
                      provider.resetPagination();
                      await provider.paymentsListsByModeAPIFunction(
                        context,
                        widget.mode,
                        "",
                      );
                    },
                    child: ListView.builder(
                      controller: _scrollController,
                      itemCount:
                          paymentLists.length + (provider.hasMoreData ? 1 : 0),
                      itemBuilder: (context, index) {
                        if (index == paymentLists.length) {
                          return provider.isLoadingMore
                              ? const Padding(
                                padding: EdgeInsets.all(16),
                                child: Center(
                                  child: CircularProgressIndicator(),
                                ),
                              )
                              : const SizedBox.shrink();
                        }

                        final payment = paymentLists[index];
                        return InkResponse(
                          onTap: () async {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => Paymentdetailsbymode(
                                      mode: widget.mode,
                                      pageTitleName: widget.pageTitleName,
                                      paymentId: paymentLists[index].paymentId,
                                    ),
                              ),
                            );
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 7.5,
                              vertical: 5,
                            ),
                            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(8.0),
                                        decoration: BoxDecoration(
                                          color: getDecorationColor(
                                            paymentLists[index].status,
                                          ),
                                          shape: BoxShape.circle,
                                        ),
                                        child: Center(
                                          child: Text(
                                            getText(paymentLists[index].status),
                                            style: TextStyle(
                                              color: getTextColor(
                                                paymentLists[index].status,
                                              ),
                                              fontSize: getSize(
                                                paymentLists[index].status,
                                              ),
                                              fontFamily: "JakartaBold",
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 10),
                                    SizedBox(width: 10),
                                    Expanded(
                                      flex: 4,
                                      child: SizedBox(
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              paymentLists[index].ename!,
                                              style: TextStyle(
                                                fontFamily: "JakartaMedium",
                                                fontSize: 14,
                                                color: AppColors.semi_black,
                                              ),
                                            ),
                                            Text(
                                              paymentLists[index].orderNumber ??
                                                  "-",
                                              style: TextStyle(
                                                fontSize: 14,
                                                color: AppColors.grey_semi,
                                                fontFamily: "JakartaRegular",
                                                decoration: TextDecoration.none,
                                                decorationColor:
                                                    AppColors.white,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      flex: 2,
                                      child: Container(
                                        child: Center(
                                          child: Text(
                                            "₹"
                                            "${paymentLists[index].amount}",
                                            textAlign: TextAlign.right,
                                            style: TextStyle(
                                              fontFamily: "JakartaMedium",
                                              fontSize: 14,
                                              color: AppColors.app_blue,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  )
                  : Emptywidget(context),
        );
      },
    );
  }

  Widget _scaffold1(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 Consumer<Paymentsprovider>(
      builder: (context, provider, child) {
        final paymentLists = provider.paymentsList;
        return WillPopScope(
          onWillPop: () {
            provider.resetAll();
            return onBackPressed(context);
          },
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS ? false : true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,
              appBar: appbar2(
                context,
                widget.pageTitleName,
                provider.resetAll,
                Row(
                  children: [
                    // InkResponse(
                    //   onTap: () {
                    //     _showOptionsSheet(context);
                    //   },
                    //   child: SvgPicture.asset("assets/svg/ic_download.svg",),
                    // ),
                    InkResponse(
                      onTap: () async {
                        _showFilterSheet(context);
                      },
                      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,
                          ),
                        ),
                      )
                      : paymentLists.isNotEmpty
                      ? SingleChildScrollView(
                        child: Column(
                          children: [
                            ListView.builder(
                              itemCount: paymentLists.length,
                              shrinkWrap: true,
                              physics: NeverScrollableScrollPhysics(),
                              itemBuilder: (context, index) {
                                if (paymentLists.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(
                                                    paymentLists[index].ename!,
                                                    style: TextStyle(
                                                      fontFamily:
                                                          "JakartaMedium",
                                                      fontSize: 14,
                                                      color:
                                                          AppColors.semi_black,
                                                    ),
                                                  ),
                                                  Text(
                                                    "₹"
                                                    "${paymentLists[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(
                                                  paymentLists[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 = [
                                          "Customer Name",
                                          "Order Number",
                                          "Date",
                                          "Description",
                                        ];

                                        final subHeadings = [
                                          paymentLists[index].aname,
                                          paymentLists[index].orderNumber,
                                          paymentLists[index].datetime,
                                          paymentLists[index].description,
                                        ];
                                        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(
                                                  child: Text(
                                                    "${subHeadings[j]}",
                                                    style: TextStyle(
                                                      fontSize: 14,
                                                      color: Color(0xFF818181),
                                                      decoration:
                                                          TextDecoration.none,
                                                      decorationColor:
                                                          AppColors.white,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                        );
                                      }),
                                      InkResponse(
                                        onTap: () async {
                                          Navigator.push(
                                            context,
                                            MaterialPageRoute(
                                              builder:
                                                  (context) =>
                                                      Paymentdetailsbymode(
                                                        mode: widget.mode,
                                                        pageTitleName:
                                                            widget
                                                                .pageTitleName,
                                                        paymentId:
                                                            paymentLists[index]
                                                                .paymentId,
                                                      ),
                                            ),
                                          );
                                        },
                                        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<Paymentsprovider>(
                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",
                              ),
                            );
                          }),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }

  Future<void> _showFilterSheet(BuildContext context) {
    return showModalBottomSheet(
      useSafeArea: true,
      isDismissible: true,
      isScrollControlled: true,
      showDragHandle: true,
      backgroundColor: Colors.white,
      enableDrag: true,
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return SafeArea(
              child: Consumer<Paymentsprovider>(
                builder: (context, provider, child) {
                  return Container(
                    padding: EdgeInsets.only(
                      bottom: MediaQuery.of(context).viewInsets.bottom,
                    ),
                    margin: EdgeInsets.only(
                      bottom: 15,
                      left: 15,
                      right: 15,
                      top: 10,
                    ),

                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Padding(
                            padding: EdgeInsets.symmetric(vertical: 10),
                            child: Text(
                              "Filter",
                              style: TextStyle(
                                color: AppColors.app_blue,
                                fontSize: 16,
                                fontFamily: "JakartaMedium",
                              ),
                            ),
                          ),

                          Text(
                            "Select Employee",
                            style: TextStyle(color: Color(0xFF2D2D2D)),
                          ),
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<Employees>(
                                    isExpanded: true,
                                    hint: Text(
                                      'Select Account Type',
                                      style: TextStyle(fontSize: 14),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    items:
                                        provider.employeesList
                                            .map(
                                              (emps) =>
                                                  DropdownMenuItem<Employees>(
                                                    value: emps,
                                                    child: Text(
                                                      emps.name ?? '',
                                                      style: const TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                    ),
                                                  ),
                                            )
                                            .toList(),
                                    value: provider.selectedEmployee,
                                    onChanged: (Employees? value) {
                                      if (value != null) {
                                        if (provider.employeesList.isNotEmpty) {
                                          provider.selectedEmployee = value;
                                          print(
                                            "Selected Complaint Type: ${value.name}, ID: ${value.id}",
                                          );
                                          provider.selectedEmpID = value.id!;
                                          provider.selectedEmpName =
                                              value.name!;
                                          print(
                                            "hfjkshfg${provider.selectedEmpID}",
                                          );
                                        }
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          InkResponse(
                            onTap: () {
                              Navigator.pop(context);
                              provider.paymentsListsByModeAPIFunction(
                                context,
                                widget.mode,
                                provider.selectedEmpID.toString(),
                              );
                            },
                            child: Container(
                              height: 45,
                              alignment: Alignment.center,
                              margin: EdgeInsets.symmetric(
                                horizontal: 10,
                                vertical: 15,
                              ),
                              padding: EdgeInsets.symmetric(
                                horizontal: 10,
                                vertical: 5,
                              ),
                              decoration: BoxDecoration(
                                color: AppColors.app_blue,
                                borderRadius: BorderRadius.circular(15),
                              ),
                              child: Text(
                                "Search",
                                style: TextStyle(
                                  fontSize: 15,
                                  fontFamily: "JakartaMedium",
                                  color: Colors.white,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
