import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/Utils/dropdownTheme.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../Models/crmModels/ProspectListViewResponse.dart';
import '../../Notifiers/crmProvider/ProspectListProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';
import 'ProspectDetailsByMode.dart';

class ProspectListByMode extends StatefulWidget {
  final pageTitleName;
  final mode;

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

  @override
  State<ProspectListByMode> createState() => _ProspectListByModeState();
}

class _ProspectListByModeState extends State<ProspectListByMode> {
  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) {
      final provider = Provider.of<ProspectListProvider>(
        context,
        listen: false,
      );
      provider.crmProspectListViewAPIFunction(context, widget.mode);
      provider.crmProspectListAPIFunction(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: () => onBackPressed(context),
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(BuildContext context) {
    return Consumer<ProspectListProvider>(
      builder: (context, provider, child) {
        final crmLists = provider.accountList;
        // ignore: deprecated_member_use
        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: appbar2New(
            context,
            widget.pageTitleName,
            provider.resetForm,
            Row(
              children: [
                InkResponse(
                  onTap: () async {
                    HapticFeedback.selectionClick();
                    _showFilterSheet(context);
                  },
                  child: SvgPicture.asset(
                    "assets/svg/filter_ic.svg",
                    height: 25,
                  ),
                ),
              ],
            ),
            0xFFFFFFFF,
          ),
          backgroundColor: AppColors.scaffold_bg_color,
          body:
              provider.isLoading
                  ? Center(
                    child: CircularProgressIndicator.adaptive(
                      valueColor: AlwaysStoppedAnimation<Color>(
                        AppColors.app_blue,
                      ),
                    ),
                  )
                  : crmLists.isNotEmpty
                  ? SizedBox(
                    child: Scrollbar(
                      thumbVisibility: false,
                      child: ListView.builder(
                        itemCount: crmLists.length,
                        shrinkWrap: true,
                        physics: AlwaysScrollableScrollPhysics(),
                        itemBuilder: (context, index) {
                          if (crmLists.isEmpty) {
                            return SizedBox(
                              child: Center(child: Text("No Data Available")),
                            );
                          }

                          // if(crmLists[index].aid=="1726"){
                          return InkResponse(
                            onTap: () async {
                              HapticFeedback.selectionClick();
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder:
                                      (context) => ProspectDetailsByMode(
                                        pageTitleName: widget.pageTitleName,
                                        mode: widget.mode,
                                        leadId: provider.accountList[index].aid,
                                      ),
                                ),
                              );
                            },
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 10,
                                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: SizedBox(
                                          height: 50,
                                          width: 35,

                                          child: SvgPicture.asset(
                                            "assets/svg/crm/lead_details_list_ic.svg",
                                          ),
                                        ),
                                      ),
                                      SizedBox(width: 10),
                                      Expanded(
                                        flex: 4,
                                        child: SizedBox(
                                          child: Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              Text(
                                                crmLists[index].aname!,
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  fontFamily: "JakartaMedium",
                                                  fontSize: 14,
                                                  color: AppColors.semi_black,
                                                ),
                                              ),
                                              Text(
                                                crmLists[index].mob1 ?? "-",
                                                maxLines: 1,
                                                style: TextStyle(
                                                  fontFamily: "JakartaMedium",
                                                  fontSize: 12,
                                                  color: AppColors.grey_semi,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                      SizedBox(width: 10),
                                      Expanded(
                                        flex: 1,
                                        child: InkResponse(
                                          onTap: () {
                                            HapticFeedback.selectionClick();
                                            launch(
                                              'tel://${crmLists[index].mob1}',
                                            );
                                          },
                                          child: SizedBox(
                                            height: 35,
                                            width: 35,
                                            child: SvgPicture.asset(
                                              "assets/svg/crm/lead_list_call_ic.svg",
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  // Divider(
                                  //   thickness: 0.5,
                                  //   color: Color(0xFFD7D7D7),
                                  // ),
                                  // ...List.generate(6, (j) {
                                  //   final headings = [
                                  //     "Account Manager",
                                  //     "Contact Person",
                                  //     "Mobile Number",
                                  //     "Address",
                                  //     "Account Age",
                                  //     "GST Number",
                                  //   ];
                                  //
                                  //   final subHeadings = [
                                  //     crmLists[index].accman,
                                  //     crmLists[index].cname,
                                  //     crmLists[index].mob1,
                                  //     crmLists[index].address,
                                  //     "${crmLists[index].age} days old",
                                  //     crmLists[index].gstNumber,
                                  //   ];
                                  //   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: Text(
                                  //             subHeadings[j]!,
                                  //             style: TextStyle(
                                  //               fontSize: 14,
                                  //               color: Color(0xFF818181),
                                  //             ),
                                  //           ),
                                  //         ),
                                  //       ],
                                  //     ),
                                  //   );
                                  // }),
                                  // InkResponse(
                                  //
                                  //   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> _showFilterSheet(BuildContext context) {
    List<bool> isSelected = List.generate(
      2,
      (index) => index == 0 ? true : false,
    );

    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: Padding(
                padding: EdgeInsets.only(
                  bottom: MediaQuery.of(context).viewInsets.bottom,
                ),
                child: Consumer<ProspectListProvider>(
                  builder: (context, provider, child) {
                    int selectedIndex = isSelected.indexWhere(
                      (element) => element == true,
                    );
                    List<String> headings = ["Mobile Number", "Company Name"];
                    if (widget.mode != "executive") {
                      headings.add("Employee");
                    }
                    return SizedBox(
                      height: MediaQuery.of(context).size.height * 0.3,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: EdgeInsets.only(left: 15),
                            child: Text(
                              "Filter",
                              style: TextStyle(
                                color: AppColors.app_blue,
                                fontSize: 18,
                                fontFamily: "JakartaSemiBold",
                              ),
                            ),
                          ),
                          const SizedBox(height: 20),
                          Expanded(
                            flex: 4,
                            child: Container(
                              decoration: BoxDecoration(
                                border: Border(
                                  top: BorderSide(
                                    color: const Color(0xFFA5DAF9),
                                  ),
                                  bottom: BorderSide(
                                    color: const Color(0xFFA5DAF9),
                                  ),
                                ),
                              ),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Expanded(
                                    flex: 3,
                                    child: Column(
                                      children: List.generate(headings.length, (
                                        jj,
                                      ) {
                                        return Expanded(
                                          child: InkResponse(
                                            onTap: () {
                                              HapticFeedback.selectionClick();
                                              setState(() {
                                                // Reset all to false
                                                isSelected = List.generate(
                                                  headings.length,
                                                  (index) => false,
                                                );
                                                // Set the clicked item to true
                                                isSelected[jj] = true;
                                              });
                                            },
                                            child: Container(
                                              padding:
                                                  const EdgeInsets.symmetric(
                                                    vertical: 7.5,
                                                    horizontal: 10,
                                                  ),
                                              decoration: BoxDecoration(
                                                border: Border(
                                                  left:
                                                      isSelected[jj]
                                                          ? BorderSide(
                                                            color:
                                                                AppColors
                                                                    .app_blue,
                                                            width: 5.0,
                                                          )
                                                          : const BorderSide(
                                                            color:
                                                                Colors
                                                                    .transparent,
                                                          ),
                                                  bottom:
                                                      jj == headings.length - 1
                                                          ? const BorderSide(
                                                            color:
                                                                Colors
                                                                    .transparent,
                                                          )
                                                          : const BorderSide(
                                                            color: Color(
                                                              0xFFA5DAF9,
                                                            ),
                                                          ),
                                                ),
                                                color: const Color(0xFFE6F6FF),
                                              ),
                                              child: Center(
                                                child: Text(
                                                  headings[jj],
                                                  textAlign: TextAlign.center,
                                                  style: TextStyle(
                                                    fontSize: 14,
                                                    fontFamily:
                                                        "JakartaRegular",
                                                    color: AppColors.semi_black,
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ),
                                        );
                                      }),
                                    ),
                                  ),
                                  Expanded(
                                    flex: 5,
                                    child: SingleChildScrollView(
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 10,
                                        vertical: 5,
                                      ),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          if (selectedIndex == 0) ...[
                                            SizedBox(height: 10),
                                            textControllerWidget(
                                              context,
                                              provider.mobileNumberController,
                                              "",
                                              "Enter Mobile Number",
                                              provider.onChangedMobileNum,
                                              TextInputType.number,
                                              false,
                                              FilteringTextInputFormatter
                                                  .digitsOnly,
                                            ),
                                          ] else if (selectedIndex == 1) ...[
                                            SizedBox(height: 10),
                                            textControllerWidget(
                                              context,
                                              provider.companyNameController,
                                              "",
                                              "Enter Company Name",
                                              provider.onChangedCompanyName,
                                              TextInputType.text,
                                              false,
                                              null,
                                            ),
                                          ] else if (widget.mode !=
                                              "executive") ...[
                                            ...provider.employeesList.map((
                                              employee,
                                            ) {
                                              return SizedBox(
                                                height: 35,
                                                child: CheckboxListTile(
                                                  activeColor:
                                                      AppColors.app_blue,
                                                  controlAffinity:
                                                      ListTileControlAffinity
                                                          .leading,
                                                  checkboxShape: CircleBorder(
                                                    side: BorderSide(
                                                      width: 0.5,
                                                    ),
                                                  ),
                                                  title: Text(
                                                    employee.name!,
                                                    style: const TextStyle(
                                                      fontSize: 14,
                                                    ),
                                                  ),
                                                  value:
                                                      provider
                                                          .selectedEmployees ==
                                                      employee,
                                                  onChanged: (bool? value) {
                                                    setState(() {
                                                      if (value == true) {
                                                        provider.selectedEmployees =
                                                            employee;
                                                        provider.selectedEmployeeId =
                                                            employee.id!;
                                                        provider.selectedEmployeeValue =
                                                            employee.name!;
                                                      }
                                                      provider.crmProspectListAPIFunction(
                                                        context,
                                                        widget.mode,
                                                        provider
                                                            .selectedEmployeeId,
                                                      );
                                                    });
                                                  },
                                                  contentPadding:
                                                      EdgeInsets.zero,
                                                ),
                                              );
                                            }),
                                          ],
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 15,
                              vertical: 20,
                            ),
                            child: InkResponse(
                              onTap: () {
                                HapticFeedback.selectionClick();
                                provider.crmProspectListAPIFunction(
                                  context,
                                  widget.mode,
                                  provider.selectedEmployeeId,
                                );
                                Navigator.pop(context);
                              },
                              child: Container(
                                height: 45,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  color: AppColors.app_blue,
                                  borderRadius: BorderRadius.circular(15),
                                ),
                                child: const Text(
                                  "Search",
                                  style: TextStyle(
                                    fontSize: 15,
                                    fontFamily: "JakartaMedium",
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ),
            );
          },
        );
      },
    );
  }

  // Future<void> _showFilterSheet11(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<ProspectListProvider>(
  //               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 + 50,
  //                   ),
  //
  //                   child: SingleChildScrollView(
  //                     child: Column(
  //                       crossAxisAlignment: CrossAxisAlignment.start,
  //                       mainAxisSize: MainAxisSize.min,
  //                       children: [
  //                         SizedBox(height: 15),
  //                         Row(
  //                           children: [
  //                             Expanded(
  //                               child: Text(
  //                                 "Filter",
  //                                 style: TextStyle(
  //                                   color: AppColors.app_blue,
  //                                   fontSize: 14,
  //                                 ),
  //                               ),
  //                             ),
  //                           ],
  //                         ),
  //
  //                         if (widget.mode != "executive") ...[
  //                           TextWidget(context, "Employee"),
  //                           DropdownButtonHideUnderline(
  //                             child: Row(
  //                               children: [
  //                                 Expanded(
  //                                   child: DropdownButton2<Employees>(
  //                                     hint: Text(
  //                                       "Select Source",
  //                                       style: TextStyle(fontSize: 14),
  //                                     ),
  //                                     items:
  //                                         provider.employeesList
  //                                             .map(
  //                                               (slist) =>
  //                                                   DropdownMenuItem<Employees>(
  //                                                     value: slist,
  //                                                     child: Text(
  //                                                       slist.name!,
  //                                                       style: TextStyle(
  //                                                         fontSize: 14,
  //                                                       ),
  //                                                     ),
  //                                                   ),
  //                                             )
  //                                             .toList(),
  //                                     value:
  //                                         provider.employeesList.contains(
  //                                               provider.selectedEmployees,
  //                                             )
  //                                             ? provider.selectedEmployees
  //                                             : null,
  //
  //                                     // value: provider.selectedEmployees,
  //                                     onChanged: (Employees? value) {
  //                                       if (value != null) {
  //                                         if (provider
  //                                             .employeesList
  //                                             .isNotEmpty) {
  //                                           provider.selectedEmployees = value;
  //                                           provider.selectedEmployeeId =
  //                                               value!.id!;
  //                                           provider.selectedEmployeeValue =
  //                                               value!.name!;
  //                                         }
  //                                       }
  //                                     },
  //                                     isExpanded: true,
  //                                     dropdownSearchData: DropdownSearchData(
  //                                       searchInnerWidgetHeight: 50,
  //                                       searchController:
  //                                           provider.searchController,
  //                                       searchInnerWidget: Padding(
  //                                         padding: const EdgeInsets.all(8),
  //                                         child: TextFormField(
  //                                           controller:
  //                                               provider.searchController,
  //                                           decoration: InputDecoration(
  //                                             isDense: true,
  //                                             contentPadding:
  //                                                 const EdgeInsets.symmetric(
  //                                                   horizontal: 10,
  //                                                   vertical: 8,
  //                                                 ),
  //                                             hintText: 'Search account...',
  //                                             border: OutlineInputBorder(
  //                                               borderRadius:
  //                                                   BorderRadius.circular(8),
  //                                             ),
  //                                           ),
  //                                         ),
  //                                       ),
  //                                       searchMatchFn: (item, searchValue) {
  //                                         return item.value?.name
  //                                                 ?.toLowerCase()
  //                                                 .contains(
  //                                                   searchValue.toLowerCase(),
  //                                                 ) ??
  //                                             false;
  //                                       },
  //                                     ),
  //                                     onMenuStateChange: (isOpen) {
  //                                       if (!isOpen) {
  //                                         provider.searchController.clear();
  //                                       }
  //                                     },
  //                                     buttonStyleData: ddtheme.buttonStyleData,
  //                                     iconStyleData: ddtheme.iconStyleData,
  //                                     menuItemStyleData:
  //                                         ddtheme.menuItemStyleData,
  //                                     dropdownStyleData:
  //                                         ddtheme.dropdownStyleData,
  //                                   ),
  //                                 ),
  //                               ],
  //                             ),
  //                           ),
  //                         ],
  //
  //                         textControllerWidget(
  //                           context,
  //                           provider.mobileNumberController,
  //                           "Mobile Number",
  //                           "Enter Mobile Number",
  //                           provider.onChangedMobileNum,
  //                           TextInputType.number,
  //                           false,
  //                           FilteringTextInputFormatter.digitsOnly,
  //                         ),
  //                         textControllerWidget(
  //                           context,
  //                           provider.companyNameController,
  //                           "Company Name",
  //                           "Enter Company Name",
  //                           provider.onChangedCompanyName,
  //                           TextInputType.text,
  //                           false,
  //                           null,
  //                         ),
  //
  //                         InkResponse(
  //                           onTap: () {
  //                             provider.crmProspectListAPIFunction(
  //                               context,
  //                               widget.mode,
  //                               provider.selectedEmployeeId,
  //                             );
  //                             Navigator.pop(context);
  //                           },
  //                           child: Container(
  //                             height: 45,
  //                             alignment: Alignment.center,
  //                             margin: EdgeInsets.symmetric(horizontal: 10),
  //                             padding: EdgeInsets.symmetric(
  //                               horizontal: 10,
  //                               vertical: 5,
  //                             ),
  //                             decoration: BoxDecoration(
  //                               color: AppColors.app_blue,
  //                               borderRadius: BorderRadius.circular(15),
  //                             ),
  //                             child: Text(
  //                               "Submit",
  //                               style: TextStyle(
  //                                 fontSize: 15,
  //                                 fontFamily: "JakartaMedium",
  //                                 color: Colors.white,
  //                               ),
  //                             ),
  //                           ),
  //                         ),
  //                       ],
  //                     ),
  //                   ),
  //                 );
  //               },
  //             ),
  //           );
  //         },
  //       );
  //     },
  //   );
  // }
}
