import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dotted_line/dotted_line.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 CrmdashboardScreenUpdated extends StatefulWidget {
  const CrmdashboardScreenUpdated({super.key});

  @override
  State<CrmdashboardScreenUpdated> createState() => _CrmdashboardScreenUpdatedState();
}

class _CrmdashboardScreenUpdatedState extends State<CrmdashboardScreenUpdated> {
  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, "executive", "", "", "");
      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/appbar_back_button.svg",
                      height: 25,
                    ),
                  ),
                  SizedBox(width: 10),
                  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: InkResponse(
                onTap: () {
                  print("Tap");
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder:
                          (context) => Universalsearchscreen(
                        text: provider.searchController.text,
                      ),
                      settings: RouteSettings(name: 'SearchScreen'),
                    ),
                  );
                },
                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),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: Container(
                          alignment: Alignment.centerLeft,
                          padding: const EdgeInsets.fromLTRB(0.0, 0.0, 10, 0),
                          margin: const EdgeInsets.fromLTRB(10.0, 0.0, 10, 10),
                          child: Text("Search",style: TextStyle(
                              color: AppColors.grey_thick,
                              fontSize:14
                          ),),
                        ),
                      ),
                      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.length > 0) ...[
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                    margin: EdgeInsets.only(bottom: 10),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.vertical(
                        bottom: Radius.circular(16),
                      ),
                    ),
                    height: MediaQuery.of(context).size.height * 0.25,
                    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: 55 / 100,
                      ),
                      itemBuilder: (context, jndex) {
                        final icons = ["comm_ic_1", "comm_ic_2"];
                        final leadTitles = [
                          'Open Leads',
                          'Quotation Generated',
                          'Pending Tasks',
                          'Today Visits',
                          'Today Calls',
                          'Hot Leads'
                              'Cold Leads',
                          'Warm Leads',
                          // 'Total Leads',
                          // 'Order Lost',
                          // 'No Requirement',
                          // 'Open Enquiries',
                        ];
                        final assetNames = [
                          "assets/svg/crm/open_leads_ic.svg",
                          "assets/svg/crm/quotes_generated_ic.svg",
                          "assets/svg/crm/pending_tasks_ic.svg",
                          "assets/svg/crm/today_visits_ic.svg",
                          "assets/svg/crm/today_calls_ic.svg",
                          "assets/svg/crm/hot_leads_ic.svg",
                          "assets/svg/crm/cold_leads_ic.svg",
                          "assets/svg/crm/warm_leads_ic.svg",
                        ];
                        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(20),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text(
                                  provider.allLeads[jndex].count.toString(),
                                  style: TextStyle(
                                    fontSize: 20,
                                    fontFamily: "JakartaMedium",
                                    color: Color(textcolors[jndex]),
                                  ),
                                ),
                                Row(
                                  children: [
                                    Expanded(
                                      flex: 3,
                                      child: Text(
                                        leadTitles[jndex],
                                        style: TextStyle(
                                          fontSize: 14,
                                          fontFamily: "JakartaRegular",
                                          color: AppColors.semi_black,
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      flex: 1,
                                      child: SvgPicture.asset(
                                        assetNames[jndex],
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ],

                // 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",
                //               ),
                //             ),
                //           ],
                //         ),
                //       ),
                //     );
                //   },
                // ),
                Container(
                  height: MediaQuery.of(context).size.height * 0.2,
                  margin: EdgeInsets.symmetric(horizontal: 10),
                  child: Row(
                    children: [
                      Expanded(
                        child: Column(
                          children: [
                            Expanded(
                              child: InkResponse(
                                onTap: () {},
                                child: Container(
                                  padding: EdgeInsets.symmetric(horizontal: 5),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(20),
                                  ),
                                  child: Row(
                                    children: [
                                      Expanded(
                                        flex: 2,
                                        child: InkResponse(
                                          onTap: () {
                                            Navigator.push(
                                              context,
                                              MaterialPageRoute(
                                                builder:
                                                    (context) => Leadlistbymode(
                                                  mode: "executive",
                                                  pageTitleName:
                                                  "Lead List",
                                                ),
                                              ),
                                            );
                                          },
                                          child: Container(
                                            padding: EdgeInsets.only(
                                              top: 15,
                                              left: 10,
                                            ),
                                            child: Column(
                                              crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                              children: [
                                                Text(
                                                  "Lead List",
                                                  style: TextStyle(
                                                    color: AppColors.app_blue,
                                                    fontSize: 14,
                                                  ),
                                                ),
                                                Text(
                                                  "Product and \nservice orders",
                                                  style: TextStyle(
                                                    color: AppColors.grey_semi,
                                                    fontSize: 12,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        child: SvgPicture.asset(
                                          "assets/svg/crm/lead_list_ic.svg",
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                            SizedBox(height: 10),
                            Expanded(
                              child: InkResponse(
                                child: Container(
                                  padding: EdgeInsets.symmetric(horizontal: 5),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(20),
                                  ),
                                  child: Row(
                                    children: [
                                      Expanded(
                                        flex: 2,
                                        child: InkResponse(
                                          onTap: () {
                                            Navigator.push(
                                              context,
                                              MaterialPageRoute(
                                                builder:
                                                    (context) =>
                                                    ProspectListByMode(
                                                      mode: "executive",
                                                      pageTitleName:
                                                      "Account List",
                                                    ),
                                              ),
                                            );
                                          },
                                          child: Container(
                                            padding: EdgeInsets.only(
                                              top: 15,
                                              left: 10,
                                            ),
                                            child: Column(
                                              crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                              children: [
                                                Text(
                                                  "Account List",
                                                  style: TextStyle(
                                                    color: AppColors.app_blue,
                                                    fontSize: 14,
                                                  ),
                                                ),
                                                Text(
                                                  "Assigned agents, \nperformance",
                                                  style: TextStyle(
                                                    color: AppColors.grey_semi,
                                                    fontSize: 12,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        child: SvgPicture.asset(
                                          "assets/svg/crm/account_list_ic.svg",
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(width: 10),
                      Expanded(
                        child: InkResponse(
                          onTap: () {},

                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 15,
                              vertical: 15,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(20),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                Expanded(
                                  child: Row(
                                    children: [
                                      Expanded(
                                        child: Text(
                                          "Appointment",
                                          style: TextStyle(
                                            color: AppColors.app_blue,
                                            fontSize: 14,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                Text(
                                  "Records,\nLedger",
                                  style: TextStyle(
                                    color: AppColors.grey_semi,
                                    fontSize: 12,
                                  ),
                                ),
                                Spacer(),
                                Expanded(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      SvgPicture.asset(
                                        "assets/svg/crm/appointment_calendar_ic.svg",
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),

                if (provider.pendingTasksLists.length > 0) ...[
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Padding(
                      padding: EdgeInsets.only(left: 15, top: 10, right: 15),
                      child: Row(
                        children: [
                          Text(
                            "Pending Tasks",
                            style: TextStyle(
                              fontSize: 16,
                              color: AppColors.grey_semi,
                            ),
                          ),
                          if (provider.pendingTasksLists.length > 5) ...[
                            Spacer(),
                            SizedBox(
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Text(
                                    "View All",
                                    style: TextStyle(
                                      fontFamily: "JakartaMedium",
                                      fontSize: 14,
                                      color: AppColors.app_blue,
                                    ),
                                  ),
                                  SizedBox(width: 5),
                                  SvgPicture.asset(
                                    "assets/svg/next_button.svg",
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ],
                      ),
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    child: ListView.builder(
                      physics: AlwaysScrollableScrollPhysics(),
                      shrinkWrap: true,
                      padding: EdgeInsets.symmetric(
                        vertical: 5,
                        horizontal: 10,
                      ),
                      itemCount: provider.pendingTasksLists.length,
                      itemBuilder: (context, index) {
                        final subHeadings = [
                          provider.pendingTasksLists[index].aname ?? "-",
                          provider.pendingTasksLists[index].appdate ?? "-",
                          provider.pendingTasksLists[index].anote ?? "-",
                        ];
                        return Container(
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(15),
                          ),
                          margin: EdgeInsets.symmetric(vertical: 3),
                          padding: EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 5,
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              ...List.generate(3, (j) {
                                return Container(
                                  padding: EdgeInsets.symmetric(
                                    vertical: 3,
                                    horizontal: 0,
                                  ),

                                  child: Column(
                                    children: [
                                      if (j == 2) ...[
                                        Padding(
                                          padding: const EdgeInsets.only(
                                            top: 3.0,
                                            bottom: 3.0,
                                          ),
                                          child: DottedLine(
                                            dashGapLength: 4,
                                            dashGapColor: Colors.white,
                                            dashColor: AppColors.grey_semi,
                                            dashLength: 4,
                                            lineThickness: 0.5,
                                          ),
                                        ),
                                      ],
                                      Row(
                                        crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                        children: [
                                          Expanded(
                                            child: Text(
                                              "${subHeadings[j]}",
                                              style: TextStyle(
                                                color:
                                                j == 0
                                                    ? AppColors.semi_black
                                                    : 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",
                              ),
                            );
                          }),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
