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/screens/crm/universalSearchScreen.dart';

import 'package:provider/provider.dart';
import 'package:generp/screens/screensExports.dart';
import '../../Notifiers/crmProvider/crmDashboardProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonServices.dart';
import '../../Utils/commonWidgets.dart';

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

  @override
  State<CrmdashboardScreen> createState() => _CrmdashboardScreenState();
}

class _CrmdashboardScreenState extends State<CrmdashboardScreen> {
  FocusNode focusNode = FocusNode();
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

  @override
  void initState() {
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((event) {
      setState(() => _source = event);
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var prov = Provider.of<Crmdashboardprovider>(context, listen: false);
      prov.accessPagesAPIFunction(context);
      prov.crmDashboardAPIFunction(context);
      prov.crmPendingTasksAPIFunction(context);
    });
  }

  @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<Crmdashboardprovider>(
      builder: (context, provider, child) {
        final gridPages =
            provider.accessPages
                .where((page) => ![8, 9, 23, 24, 51, 50].contains(page.id))
                .toList();

        return Scaffold(
          resizeToAvoidBottomInset: true,
          backgroundColor: AppColors.scaffold_bg_color,
          appBar: AppBar(
            automaticallyImplyLeading: false,
            elevation: 2.0,
            title: SizedBox(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  InkResponse(
                    onTap: () => Navigator.pop(context, true),
                    child: SvgPicture.asset(
                      "assets/svg/app_bar_back.svg",
                      height: 25,
                    ),
                  ),
                  InkResponse(
                    onTap: () => Navigator.pop(context, true),
                    child: Text(
                      "CRM",
                      style: TextStyle(
                        fontSize: 16,
                        height: 1.1,
                        fontFamily: "JakartaSemiBold",
                        color: AppColors.semi_black,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            bottom: PreferredSize(
              preferredSize: Size.fromHeight(50),
              child: Container(
                padding: const EdgeInsets.fromLTRB(5.0, 0.0, 10, 0),
                margin: const EdgeInsets.fromLTRB(10.0, 0.0, 10, 10),
                height: 50,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: AppColors.text_field_color,
                  borderRadius: BorderRadius.circular(14),
                  border:
                      focusNode.hasFocus
                          ? Border.all(color: AppColors.app_blue)
                          : null,
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10, 0),
                        margin: const EdgeInsets.fromLTRB(10.0, 0.0, 10, 10),
                        child: TextFormField(
                          controller: provider.searchController,
                          keyboardType: TextInputType.text,
                          maxLines: 1,

                          onChanged: (value) {},
                          focusNode: focusNode,
                          onTapUpOutside: (event) {
                            focusNode.unfocus();
                          },

                          textInputAction: TextInputAction.done,
                          onEditingComplete: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => Universalsearchscreen(
                                      text: provider.searchController.text,
                                    ),
                                settings: RouteSettings(name: 'SearchScreen'),
                              ),
                            );
                          },
                          decoration: InputDecoration(
                            counterText: "",
                            hintText: "Search",
                            hintStyle: TextStyle(
                              fontWeight: FontWeight.w400,
                              color: Color(0xFFB4BEC0),
                              fontSize: 14,
                            ),
                            enabled: true,

                            enabledBorder: InputBorder.none,
                            focusedBorder: InputBorder.none,
                          ),
                        ),
                      ),
                    ),
                    SvgPicture.asset("assets/svg/search_ic.svg"),
                  ],
                ),
              ),
            ),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.vertical(
                bottom: Radius.circular(30), // Adjust the radius as needed
              ),
            ),
          ),
          body: SingleChildScrollView(
            physics: AlwaysScrollableScrollPhysics(),
            child: Column(
              children: [
                if (provider.allLeads.isNotEmpty) ...[
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                    margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(16),
                    ),
                    height: MediaQuery.of(context).size.height * 0.28,
                    child: GridView.builder(
                      padding: EdgeInsets.symmetric(horizontal: 0, vertical: 5),
                      itemCount: provider.allLeads.length,
                      shrinkWrap: true,
                      scrollDirection: Axis.horizontal,
                      physics: AlwaysScrollableScrollPhysics(),
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        crossAxisSpacing: 10,
                        mainAxisSpacing: 10,
                        childAspectRatio: 0.65,
                      ),
                      itemBuilder: (context, jndex) {
                        final icons = ["comm_ic_1", "comm_ic_2"];
                        final leadTitles = [
                          'Hot Leads',
                          'Cold Leads',
                          'Warm Leads',
                          'Total Leads',
                          'Order Lost',
                          'No Requirement',
                          'Open Enquiries',
                        ];
                        final colors = [
                          0xFFE7FFE5,
                          0xFFF3EDFF,
                          0xFFFFFCD5,
                          0xFFFFF6F0,
                          0xFFE7FFE5,
                          0xFFF3EDFF,
                          0xFFFFFCD5,
                          0xFFFFF6F0,
                        ];
                        final textcolors = [
                          0xFF0D9C00,
                          0xFF493272,
                          0xFF605C00,
                          0xFF91481B,
                          0xFF0D9C00,
                          0xFF493272,
                          0xFF605C00,
                          0xFF91481B,
                        ];
                        return InkResponse(
                          onTap: () async {
                            if (provider.allLeads[jndex].filter!.pageName !=
                                "") {
                              if (provider.allLeads[jndex].filter!.pageName!
                                  .contains("Lead List")) {
                                await Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder:
                                        (context) => Leadlistbymode(
                                          pageTitleName:
                                              provider
                                                  .allLeads[jndex]
                                                  .filter!
                                                  .pageName!,
                                          mode:
                                              provider
                                                  .allLeads[jndex]
                                                  .filter!
                                                  .mode,
                                          filter:
                                              provider.allLeads[jndex].filter!,
                                        ),
                                  ),
                                );
                              }
                            }
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(horizontal: 13),
                            decoration: BoxDecoration(
                              color: Color(colors[jndex]),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text(
                                  provider.allLeads[jndex].count!,
                                  style: TextStyle(
                                    fontSize: 30,
                                    fontFamily: "JakartaMedium",
                                    color: Color(textcolors[jndex]),
                                  ),
                                ),
                                Text(
                                  leadTitles[jndex],
                                  style: TextStyle(color: Color(0xFF818181)),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ],
                ListView.builder(
                  physics: NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                  itemCount: gridPages.length,
                  itemBuilder: (context, index) {
                    // final icons = ["comm_ic_1", "comm_ic_2"];
                    Widget? SvgIcon;

                    if (gridPages[index].pageName!.contains("Lead List")) {
                      SvgIcon = SvgPicture.asset("assets/svg/fin_lv1.svg");
                    } else if (gridPages[index].pageName == "Nearby Leads") {
                      SvgIcon = SvgPicture.asset(
                        "assets/svg/home_icons_5.svg",
                        height: 18,
                        width: 18,
                      );
                    } else {
                      SvgIcon = SvgPicture.asset("assets/svg/fin_ic.svg");
                    }
                    return InkResponse(
                      onTap: () {
                        print(gridPages[index].pageName!);
                        if (gridPages[index].pageName!.contains("Lead List")) {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder:
                                  (context) => Leadlistbymode(
                                    mode: gridPages[index].mode,
                                    pageTitleName: gridPages[index].pageName,
                                  ),
                            ),
                          );
                        } else if (gridPages[index].pageName!.contains(
                          "Account List",
                        )) {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder:
                                  (context) => ProspectListByMode(
                                    mode: gridPages[index].mode,
                                    pageTitleName: gridPages[index].pageName,
                                  ),
                            ),
                          );
                        } else if (gridPages[index].pageName ==
                            "Nearby Leads") {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => NearbyOpenLeads(),
                            ),
                          );
                        }
                        // switch (gridPages[index].pageName!) {
                        //   case "Lead List":
                        //     Navigator.push(
                        //       context,
                        //       MaterialPageRoute(builder: (context) => Leadlistbymode()),
                        //     );
                        //     break;
                        //   case "Prospect List":
                        //     // Navigator.push(
                        //     //   context,
                        //     //   MaterialPageRoute(builder: (context) => Accountledger()),
                        //     // );
                        //     break;
                        //
                        //   default:
                        //     print("111");
                        //     break;
                        // }
                      },
                      child: Container(
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(14),
                        ),
                        margin: EdgeInsets.symmetric(
                          horizontal: 5,
                          vertical: 5,
                        ),
                        padding: EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 15,
                        ),
                        child: Row(
                          children: [
                            Expanded(flex: 1, child: SvgIcon),

                            Expanded(
                              flex: 5,
                              child: Text(
                                "${gridPages[index].pageName}",
                                style: TextStyle(fontSize: 14),
                              ),
                            ),
                            Expanded(
                              flex: 1,
                              child: SvgPicture.asset(
                                "assets/svg/arrow_right_new.svg",
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                ),

                if (provider.pendingTasksLists.isNotEmpty) ...[
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 6),
                      child: Text(
                        "Pending Tasks",
                        style: TextStyle(
                          fontSize: 16,
                          color: AppColors.grey_semi,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    width: double.infinity,
                    height: MediaQuery.of(context).size.height * 0.34,
                    child: ListView.builder(
                      physics: AlwaysScrollableScrollPhysics(),
                      shrinkWrap: true,
                      scrollDirection: Axis.horizontal,
                      padding: EdgeInsets.symmetric(
                        vertical: 10,
                        horizontal: 10,
                      ),
                      itemCount: provider.pendingTasksLists.length,
                      itemBuilder: (context, index) {
                        final headings = [
                          "Lead Name",
                          "Mobile Number",
                          "Appointment Date",
                          "Appointment Type",
                          "Note",
                          "Status",
                        ];
                        final subHeadings = [
                          provider.pendingTasksLists[index].aname ?? "-",
                          provider.pendingTasksLists[index].conmob ?? "-",
                          provider.pendingTasksLists[index].appdate ?? "-",
                          provider.pendingTasksLists[index].atype ?? "-",
                          provider.pendingTasksLists[index].anote ?? "-",
                          provider.pendingTasksLists[index].lstatus ?? "-",
                        ];
                        return Container(
                          height: MediaQuery.of(context).size.height * 0.3,
                          width: MediaQuery.of(context).size.width * 0.6,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(14),
                          ),
                          margin: EdgeInsets.symmetric(
                            horizontal: 5,
                            vertical: 5,
                          ),
                          padding: EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 15,
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              ...List.generate(headings.length, (j) {
                                return Container(
                                  padding: EdgeInsets.symmetric(
                                    vertical: 6,
                                    horizontal: 0,
                                  ),
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Expanded(
                                        child: Text(
                                          headings[j],
                                          style: TextStyle(fontSize: 14),
                                        ),
                                      ),
                                      Expanded(
                                        child: Text(
                                          subHeadings[j],
                                          style: TextStyle(
                                            color: AppColors.grey_semi,
                                            fontSize: 14,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              }),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                ],
                SizedBox(height: 150),
              ],
            ),
          ),
          floatingActionButtonLocation:
              FloatingActionButtonLocation.centerFloat,
          floatingActionButton: InkResponse(
            onTap: () {
              if (provider.accessPages
                  .where((page) => [8, 9].contains(page.id))
                  .toList()
                  .contains([8, 9])) {
                _showPaymentOptionsSheet(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(
                "Add Leads and Prospect",
                style: TextStyle(
                  fontSize: 15,
                  fontFamily: "JakartaMedium",
                  color: Colors.white,
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Future<void> _showPaymentOptionsSheet(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<Crmdashboardprovider>(
                builder: (context, provider, child) {
                  final accessiblePagesList =
                      provider.accessPages
                          .where((page) => [8, 9].contains(page.id))
                          .toList();
                  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(accessiblePagesList.length, (index) {
                            print(accessiblePagesList[index].mode);

                            return ListTile(
                              onTap: () async {
                                Navigator.pop(context);
                                var res;
                              },
                              leading: SvgPicture.asset(
                                "assets/svg/fin_ic.svg",
                              ),
                              title: Text(
                                "${accessiblePagesList[index].pageName}",
                                style: TextStyle(
                                  fontSize: 14,
                                  fontFamily: "JakartaMedium",
                                ),
                              ),
                              trailing: SvgPicture.asset(
                                "assets/svg/arrow_right_new.svg",
                              ),
                            );
                          }),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
