import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/commonProvider/accountsListProvider.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:generp/screens/commom/accountsListDetails.dart';
import 'package:provider/provider.dart';

class Accountslist extends StatefulWidget {
  const Accountslist({super.key});

  @override
  State<Accountslist> createState() => _AccountslistState();
}

class _AccountslistState extends State<Accountslist> {
  final ScrollController _scrollController = ScrollController();
  int _currentPage = 1;
  bool _isLoadingMore = false;
  bool _hasMoreItems = true;

  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

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

    _scrollController.addListener(_scrollListener);

    // fetch first page once
    Future.microtask(() {
      final provider = Provider.of<Accountslistprovider>(
        context,
        listen: false,
      );
      provider.commonAccountListAPIFunction(context);
    });
  }

  @override
  void dispose() {
    _scrollController.removeListener(_scrollListener);
    _scrollController.dispose();
    _connectivity.disposeStream();
    super.dispose();
  }

  void _scrollListener() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent) {
      _loadMoreItems(context);
    }
  }

  void _loadMoreItems(BuildContext context) {
    if (_isLoadingMore || !_hasMoreItems) return;

    final provider = Provider.of<Accountslistprovider>(context, listen: false);

    setState(() {
      _isLoadingMore = true;
      _currentPage++;
    });

    provider
        .commonAccountListAPIFunction(context, append: true)
        .then((_) {
          setState(() {
            _isLoadingMore = false;
            final newItems = provider.accountsList;
            if (newItems.length < _currentPage * 15) {
              //api gives 15 records
              _hasMoreItems = false;
            }
          });
        })
        .catchError((_) {
          setState(() {
            _isLoadingMore = false;
            _currentPage--; // rollback
          });
        });
  }

  void _refreshList(BuildContext context) {
    final provider = Provider.of<Accountslistprovider>(context, listen: false);
    setState(() {
      _currentPage = 1;
      _hasMoreItems = true;
      _isLoadingMore = false;
    });
    provider.commonAccountListAPIFunction(context);
  }

  @override
  Widget build(BuildContext context) {
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.mobile:
      case ConnectivityResult.wifi:
        connection = 'Online';
        break;
      case ConnectivityResult.none:
      default:
        connection = 'Offline';
    }

    return (connection == "Online")
        ? Platform.isAndroid
            ? WillPopScope(
      onWillPop: () async {
        onBackPressed(context);
        _refreshList(context);
        final provider = Provider.of<Accountslistprovider>(context, listen: false);
        provider.resetValues();
        provider.commonAccountListAPIFunction(context);
        // Return true or false depending on whether you want to allow the pop
        return true; // allow the back navigation
        // return false; // prevent back navigation
      },

      child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(BuildContext context) {
    return Consumer<Accountslistprovider>(
      builder: (context, provider, child) {
        final accountList = provider.accountsList;

        if (provider.isLoading && _currentPage == 1) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator()),
          );
        }

        if (accountList.isEmpty) {
          return Scaffold(body: Emptywidget(context));
        }

        return Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: appbar2New(
            context,
            "Account List",
            provider.resetValues,
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 5),
              child: InkResponse(
                onTap: () {
                  _showFilterSheet1(context);
                },
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: SvgPicture.asset(
                    "assets/svg/filter_ic.svg",
                    height: 18,
                  ),
                ),
              ),
            ),
            0xFFFFFFFF,
          ),
          backgroundColor: AppColors.scaffold_bg_color,
          body: RefreshIndicator(
            onRefresh: () async => _refreshList(context),
            child: ListView.builder(
              controller: _scrollController,
              padding: const EdgeInsets.all(12),
              itemCount: accountList.length + (_hasMoreItems ? 1 : 0),
              itemBuilder: (context, index) {
                if (index >= accountList.length) {
                  return Padding(
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    child: Center(
                      child:
                          _isLoadingMore
                              ? const CircularProgressIndicator(
                                color: Colors.blue,
                              )
                              : !_hasMoreItems
                              ? const Text("No more accounts to load")
                              : const SizedBox.shrink(),
                    ),
                  );
                }

                final account = accountList[index];
                return InkResponse(
                  onTap: () async {
                    print("length, ${accountList.length}");
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder:
                            (context) => Accountslistdetails(
                              accountID: accountList[index].id,
                            ),
                      ),
                    );
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 5, vertical: 5),
                    margin: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Row(
                      children: [
                        // Expanded(
                        //   flex: 1,
                        //   child: Container(
                        //     height: 50,
                        //     width: 35,
                        //     padding: EdgeInsets.all(8.0),
                        //     decoration: BoxDecoration(
                        //       color: Color(0xFFEAF7FF),
                        //       borderRadius:
                        //           BorderRadius.circular(8),
                        //     ),
                        //     child: SvgPicture.asset(
                        //       "assets/svg/common_ac_list_ic.svg",
                        //     ),
                        //   ),
                        // ),
                        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: 7,
                          child: SizedBox(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  accountList[index].name!,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                    fontFamily: "JakartaRegular",
                                    fontSize: 14,
                                    color: AppColors.semi_black,
                                  ),
                                ),
                                Text(
                                  accountList[index].type ?? "-",
                                  maxLines: 1,
                                  style: TextStyle(
                                    fontFamily: "JakartaRegular",
                                    fontSize: 12,
                                    color: AppColors.grey_semi,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        );
      },
    );
  }

  Future<void> _showFilterSheet1(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<Accountslistprovider>(
                  builder: (context, provider, child) {
                    int selectedIndex = isSelected.indexWhere(
                      (element) => element == true,
                    );
                    List<String> headings = ["Account Name", "Mobile Number"];

                    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: () {
                                              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.companyNameController,
                                              "",
                                              "Enter Account Name",
                                              provider.onChangedCompanyName,
                                              TextInputType.text,
                                              false,
                                              null,
                                            ),
                                          ] else if (selectedIndex == 1) ...[
                                            SizedBox(height: 10),
                                            textControllerWidget(
                                              context,
                                              provider.mobileNumberController,
                                              "",
                                              "Enter Mobile Number",
                                              provider.onChangedMobileNum,
                                              TextInputType.number,
                                              false,
                                              FilteringTextInputFormatter
                                                  .digitsOnly,
                                            ),
                                          ],
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 15,
                              vertical: 20,
                            ),
                            child: InkResponse(
                              onTap: () {
                                provider.pageNum = 1;
                                provider.commonAccountListAPIFunction(context);
                                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,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ),
            );
          },
        );
      },
    );
  }
}

// Divider(
//   thickness: 0.5,
//   color: Color(0xFFD7D7D7),
// ),
// ...List.generate(4, (j) {
//   final headings = [
//     "Mobile Number",
//     "Email Id",
//     "Address",
//     "Account Type",
//   ];
//
//   final subHeadings = [
//     accountList[index].mob1 ?? "-",
//     accountList[index].email ?? "-",
//     accountList[index].address ?? "-",
//     accountList[index].type ?? "-",
//   ];
//   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,
//             ),
//           ),
//         ),
//         SizedBox(width: 15),
//         Expanded(
//           child: Text(
//             subHeadings[j] ?? "-",
//             style: TextStyle(
//               fontFamily: "JakartaMedium",
//               fontSize: 14,
//               color: AppColors.grey_thick,
//             ),
//           ),
//         ),
//       ],
//     ),
//   );
// }),
// 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",
//         ),
//       ],
//     ),
//   ),
// ),
