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/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> {
  ScrollController scrollController = ScrollController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var provider = Provider.of<Accountslistprovider>(context, listen: false);
      provider.commonAccountListAPIFunction(context);
      scrollController.addListener(() {
        if (scrollController.position.maxScrollExtent ==
            scrollController.offset) {
          provider.commonAccountListAPIFunction(context);
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<Accountslistprovider>(
      builder: (context, provider, child) {
        var accountList = provider.accountsList;
        print(accountList.length);
        return WillPopScope(
          child: Scaffold(
            resizeToAvoidBottomInset: true,
            appBar: appbar2(context, "Account List",provider.resetValues,Container(
              padding: EdgeInsets.symmetric(horizontal: 5, vertical: 5),

              child: InkResponse(
                onTap: () {
                  _showFilterSheet(context);
                },
                child: SvgPicture.asset("assets/svg/filter_ic.svg", height: 18),
              ),
            ),),
            backgroundColor: AppColors.scaffold_bg_color,
            body:SafeArea(child: accountList.isNotEmpty? SizedBox(
              child: SingleChildScrollView(
                controller: scrollController,
                child: Column(
                  children: [
                    ListView.builder(
                      itemCount: accountList.length + 1,
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemBuilder: (context, index) {
                        if (accountList.isEmpty) {
                          return SizedBox(
                            child: Center(child: Text("No Data Available")),
                          );
                        }
                        if (index == accountList.length &&
                            !provider.isLoading) {
                          return Padding(
                            padding: EdgeInsets.all(8.0),
                            child: Center(child: CircularProgressIndicator.adaptive(
                              valueColor:  AlwaysStoppedAnimation<Color>(
                                  AppColors.app_blue),
                            )),
                          );
                        }

                        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(0xFFEAF7FF),
                                        borderRadius: BorderRadius.circular(8),
                                      ),
                                      child: SvgPicture.asset(
                                        "assets/svg/common_ac_list_ic.svg",
                                      ),
                                    ),
                                  ),
                                  SizedBox(width: 10),
                                  Expanded(
                                    flex: 4,
                                    child: SizedBox(
                                      child: Column(
                                        crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            accountList[index].name!,
                                            style: TextStyle(
                                              fontFamily: "JakartaMedium",
                                              fontSize: 14,
                                              color: AppColors.semi_black,
                                            ),
                                          ),
                                          Text(
                                            accountList[index].contactName ??
                                                "-",
                                            style: TextStyle(
                                              fontFamily: "JakartaMedium",
                                              fontSize: 14,
                                              color: AppColors.app_blue,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              Divider(thickness: 0.5, color: Color(0xFFD7D7D7)),
                              ...List.generate(4, (j) {
                                final headings = [
                                  "Mobile Number",
                                  "Email Id",
                                  "Address",
                                  "Date",
                                ];

                                final subHeadings = [
                                  accountList[index].mob1 ?? "-",
                                  accountList[index].email ?? "-",
                                  accountList[index].address ?? "-",
                                  accountList[index].datetime ?? "-",
                                ];
                                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(
                                onTap: () async {
                                  print("length, ${accountList.length}");
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder:
                                          (context) => Accountslistdetails(
                                        accountID: accountList[index].id,
                                      ),
                                    ),
                                  );
                                },
                                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),)
          ),
          onWillPop: () {
            provider.pageNum = 1;
            return _onBackPressed(context);
          },
        );
      },
    );
  }


  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<Accountslistprovider>(
                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",
                              ),
                            ),
                          ),
                          textControllerWidget(context, provider.companyNameController, "Company Name", (p0) {

                          },TextInputType.text,false,null),
                          textControllerWidget(context, provider.mobileNumberController, "Mobile Number", (p0) {

                          },TextInputType.number,false,FilteringTextInputFormatter.digitsOnly),
                          InkResponse(
                            onTap: () {
                              Navigator.pop(context);
                              provider.commonAccountListAPIFunction(context);
                              provider.companyNameController.clear();
                              provider.mobileNumberController.clear();
                            },
                            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,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }


  Future<bool> _onBackPressed(BuildContext context) async {
    Provider.of<Accountslistprovider>(context, listen: false).pageNum = 1;
    Navigator.pop(context, true);
    return true;
  }
}
