import 'dart:io';

import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/screens/order/ordersDetailsByModes.dart';
import 'package:provider/provider.dart';

import '../../Models/ordersModels/ordersListByModeFilterResponse.dart';
import '../../Notifiers/ordersProvider/pagesDashboardProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';
import '../../Utils/dropdownTheme.dart';
import '../commonDateRangeFilter.dart';

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

class OrderslistbyModes extends StatefulWidget {
  final mode;
  final pageTitleName;

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

  @override
  State<OrderslistbyModes> createState() => _OrderslistbyModesState();
}

class _OrderslistbyModesState extends State<OrderslistbyModes> {
  Dropdowntheme ddtheme = Dropdowntheme();
  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) {
      var provider = Provider.of<Pagesdashboardprovider>(
        context,
        listen: false,
      );
      provider.ordersListByModeFilterAPIFunction(context, widget.mode);
      provider.ordersListByModeAPIFunction(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: () {
                Provider.of<Pagesdashboardprovider>(context).resetAll();
                return onBackPressed(context);
              },
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(BuildContext context) {
    return Consumer<Pagesdashboardprovider>(
      builder: (context, provider, child) {
        final ordersList = provider.ordersList;
        return 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,
                      ),
                    ),
                  )
                  : ordersList.isNotEmpty
                  ? SingleChildScrollView(
                    child: Column(
                      children: [
                        ListView.builder(
                          itemCount: ordersList.length,
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          itemBuilder: (context, index) {
                            if (ordersList.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(
                                                ordersList[index].accountName!,
                                                style: TextStyle(
                                                  fontFamily: "JakartaMedium",
                                                  fontSize: 14,
                                                  color: AppColors.semi_black,
                                                ),
                                              ),
                                              Text(
                                                "₹"
                                                "${ordersList[index].balanceAmount}",
                                                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(
                                              ordersList[index].status!,
                                              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 = [
                                      "Order Number",
                                      "Entered Employee",
                                      "Sales Person",
                                      // "Date",
                                      "Paid Amount",
                                      "Balance Amount",
                                    ];

                                    final subHeadings = [
                                      ordersList[index].orderNumber,
                                      ordersList[index].enteredEmpName,
                                      ordersList[index].salesPersonEmpName,
                                      // ordersList[index].createdDatetime,
                                      ordersList[index].paidAmount,
                                      ordersList[index].balanceAmount,
                                    ];
                                    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 {
                                      var res = await Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder:
                                              (context) => Ordersdetailsbymodes(
                                                pageTitleName:
                                                    widget.pageTitleName,
                                                orderId:
                                                    ordersList[index].orderId,
                                                mode: widget.mode,
                                              ),
                                        ),
                                      );
                                      if (res == true) {
                                        provider
                                            .ordersListByModeFilterAPIFunction(
                                              context,
                                              widget.mode,
                                            );
                                        provider.ordersListByModeAPIFunction(
                                          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<Pagesdashboardprovider>(
                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<Pagesdashboardprovider>(
                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",
                              ),
                            ),
                          ),
                          if ([
                            "admin",
                            "teamleader",
                          ].contains(widget.mode)) ...[
                            Text(
                              "Select Status",
                              style: TextStyle(color: Color(0xFF2D2D2D)),
                            ),
                            DropdownButtonHideUnderline(
                              child: Row(
                                children: [
                                  Expanded(
                                    child: DropdownButton2<String>(
                                      isExpanded: true,
                                      hint: const Row(
                                        children: [
                                          Expanded(
                                            child: Text(
                                              'Select Account',
                                              style: TextStyle(fontSize: 14),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                        ],
                                      ),
                                      items:
                                          provider.leadStatus
                                              .map(
                                                (status) =>
                                                    DropdownMenuItem<String>(
                                                      value: status,
                                                      child: Text(
                                                        status,
                                                        style: const TextStyle(
                                                          fontSize: 14,
                                                        ),
                                                        overflow:
                                                            TextOverflow
                                                                .ellipsis,
                                                      ),
                                                    ),
                                              )
                                              .toList(),
                                      value:
                                          provider.leadStatus.contains(
                                                provider.selectedLeadType,
                                              )
                                              ? provider.selectedLeadType
                                              : null,
                                      onChanged: (value) {
                                        if (value != null) {
                                          provider.selectedLeadType = value;
                                          print(
                                            "statusId:${provider.selectedLeadType}",
                                          );
                                        }
                                      },
                                      buttonStyleData: ddtheme.buttonStyleData,
                                      iconStyleData: ddtheme.iconStyleData,
                                      menuItemStyleData:
                                          ddtheme.menuItemStyleData,
                                      dropdownStyleData:
                                          ddtheme.dropdownStyleData,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                          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
                                                    .toString(),
                                          );
                                        }
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          InkResponse(
                            onTap: () {
                              Navigator.pop(context);
                              provider.ordersListByModeAPIFunction(
                                context,
                                widget.mode,
                                provider.selectedEmpID,
                                provider.selectedLeadType,
                              );
                            },
                            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,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
