import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/screens/crm/ProspectDetailsByMode.dart';
import 'package:provider/provider.dart';

import '../../Notifiers/crmProvider/crmDashboardProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';

class Universalsearchscreen extends StatefulWidget {
  final text;

  const Universalsearchscreen({super.key, required this.text});

  @override
  State<Universalsearchscreen> createState() => _UniversalsearchscreenState();
}

class _UniversalsearchscreenState extends State<Universalsearchscreen> {
  FocusNode focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var prov = Provider.of<Crmdashboardprovider>(context, listen: false);
      // prov.crmUniversalSearchFunction(context);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<Crmdashboardprovider>(
      builder: (context, provider, child) {
        return WillPopScope(
          onWillPop: () => onBackPressed(context),
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS ? false : true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,
              backgroundColor: AppColors.scaffold_bg_color,
              appBar: AppBar(
                backgroundColor: Colors.white,
                automaticallyImplyLeading: false,
                toolbarHeight: 20,
              ),
              body: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(

                      // padding: const EdgeInsets.fromLTRB(5.0, 0.0, 10, 0),
                      // margin: const EdgeInsets.fromLTRB(10.0, 0.0, 10, 10),
                      padding: const EdgeInsets.fromLTRB(
                        10.0,
                        0.0,
                        10,
                        10,
                      ),
                      height: 55,
                      decoration: BoxDecoration(
                        color: AppColors.white,
                        borderRadius: BorderRadius.vertical(
                          bottom: Radius.circular(14),
                        ),
                      ),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Expanded(
                            flex: 1,
                            child: InkResponse(
                              onTap: () => Navigator.pop(context, true),
                              child: Container(

                                  child: SvgPicture.asset("assets/svg/appbar_back_button.svg", height: 25)),
                            ),
                          ),
                          Expanded(
                            flex: 9,
                            child: Container(
                              padding: const EdgeInsets.fromLTRB(
                                0.0,
                                0.0,
                                10,
                                0,
                              ),

                              child: TextFormField(
                                controller: provider.searchController,
                                keyboardType: TextInputType.text,
                                maxLines: 1,
                                autofocus: true,
                                onChanged: (value) {
                                  Future.delayed(
                                    Duration(milliseconds: 500),
                                    () {
                                      provider.crmUniversalSearchFunction(
                                        context,
                                      );
                                    },
                                  );
                                },
                                focusNode: focusNode,
                                onTapUpOutside: (event) {
                                  focusNode.unfocus();
                                },

                                textInputAction: TextInputAction.done,
                                onEditingComplete: () {
                                  provider.crmUniversalSearchFunction(context);
                                },
                                decoration: InputDecoration(
                                  filled: true,
                                  fillColor: AppColors.text_field_color,
                                  suffixIconConstraints: BoxConstraints(
                                    minWidth: 25,
                                    maxWidth: 30,
                                    minHeight: 25,
                                    maxHeight: 30,
                                  ),
                                  suffixIcon: Container(
                                    padding: EdgeInsets.only(right: 10),
                                    child:provider.searchController.text.isNotEmpty?
                                    InkResponse(
                                      onTap: () {
                                        provider.searchController.clear();
                                        provider.crmUniversalSearchFunction(
                                          context,
                                        );
                                      },
                                      child: SvgPicture.asset(
                                        "assets/svg/crm/clear_search.svg",
                                      ),
                                    ):
                                    SvgPicture.asset(
                                      "assets/svg/search_ic.svg",
                                    ),
                                  ),
                                  counterText: "",
                                  hintText: "Search By Name/Mobile",
                                  hintStyle: TextStyle(
                                    fontWeight: FontWeight.w400,
                                    color: Color(0xFFB4BEC0),
                                    fontSize: 14,
                                  ),
                                  enabled: true,
                                  enabledBorder: OutlineInputBorder(
                                    borderSide: BorderSide.none,
                                    borderRadius: BorderRadius.circular(14),
                                  ),
                                  focusedBorder: OutlineInputBorder(
                                    borderSide: BorderSide(
                                      color: AppColors.cyan_blue,
                                    ),
                                    borderRadius: BorderRadius.circular(14),
                                  ),
                                  border: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(14),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    if (provider.searchController.text.isNotEmpty) ...[
                      Container(
                        alignment: Alignment.topLeft,
                        padding: EdgeInsets.only(left: 10, top: 10, bottom: 5),
                        child: Text(
                          "Results for Result for “${provider.searchController.text}”",
                          style: TextStyle(
                            color: AppColors.app_blue,
                            fontSize: 16,
                          ),
                        ),
                      ),
                    ],
                    if (provider.accountsList.length > 0) ...[
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Padding(
                          padding: EdgeInsets.symmetric(horizontal: 10),
                          child: Text(
                            "Accounts",
                            style: TextStyle(
                              fontSize: 16,
                              color: AppColors.grey_thick,
                            ),
                          ),
                        ),
                      ),
                      ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        padding: EdgeInsets.symmetric(
                          vertical: 5,
                          horizontal: 5,
                        ),
                        itemCount: provider.accountsList.length,
                        itemBuilder: (context, index) {
                          String accname = provider.accountsList[index].aname ?? "";
                          RegExp regex =
                          RegExp(provider.searchController.text, caseSensitive: false);
                          Iterable<Match> matches =
                          regex.allMatches(accname);

                          List<TextSpan> textSpans = [];
                          int previousMatchEnd = 0;

                          for (Match match in matches) {
                            if (match.start > previousMatchEnd) {
                              // Add non-matching text before this match
                              textSpans.add(
                                TextSpan(
                                  text: accname.substring(
                                      previousMatchEnd, match.start),
                                  style: TextStyle(
                                    color: AppColors.semi_black,
                                    fontSize: 12,
                                    fontFamily: "JakartaMedium",
                                  ),
                                ),
                              );
                            }

                            // Add the matching text with highlighting
                            textSpans.add(
                              TextSpan(
                                text: accname.substring(
                                    match.start, match.end),
                                style: TextStyle(
                                  color: AppColors.app_blue,
                                  fontSize: 12, // Highlight color
                                  fontFamily: "JakartaMedium",
                                ),
                              ),
                            );

                            previousMatchEnd = match.end;
                          }

                          // Add any remaining non-matching text after the last match
                          if (previousMatchEnd < accname.length) {
                            textSpans.add(
                              TextSpan(
                                text: accname.substring(previousMatchEnd),
                                style: TextStyle(
                                  color: AppColors.semi_black,
                                  fontSize: 12,
                                  fontFamily: "JakartaMedium",
                                ),
                              ),
                            );
                          }
                          return InkResponse(
                            onTap: () {
                              Navigator.pushAndRemoveUntil(
                                context,
                                MaterialPageRoute(
                                  builder:
                                      (context) => ProspectDetailsByMode(
                                        pageTitleName: "Account Details",
                                        mode: "Executive",
                                        leadId:
                                            provider.accountsList[index].aid,
                                      ),
                                  settings: RouteSettings(
                                    name: 'ProspectDetails',
                                  ),
                                ),
                                (Route<dynamic> route) =>
                                    route.settings.name == 'CrmdashboardScreen',
                              );
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(14),
                              ),

                              margin: EdgeInsets.only(
                                bottom: 5,
                                left: 5,
                                right: 5,
                                top: 5,
                              ),
                              padding: EdgeInsets.only(
                                bottom:
                                    MediaQuery.of(context).viewInsets.bottom,
                              ),
                              child: ListTile(
                                leading: SvgPicture.asset(
                                  "assets/svg/crm/crm_search_list_ic.svg",
                                ),
                                title:RichText(text: TextSpan(
                                  children: textSpans,
                                 style:  TextStyle(
                                    color: AppColors.semi_black,
                                    fontSize: 12, // Highlight color
                                    fontFamily: "JakartaMedium",
                                  ),
                                )),
                                // trailing: SvgPicture.asset(
                                //   "assets/svg/arrow_right_new.svg",
                                // ),
                              ),
                            ),
                          );
                        },
                      ),
                    ],

                    if (provider.leadsList.length > 0) ...[
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Padding(
                          padding: EdgeInsets.symmetric(horizontal: 10),
                          child: Text(
                            "Leads",
                            style: TextStyle(
                              fontSize: 16,
                              color: AppColors.grey_thick,
                            ),
                          ),
                        ),
                      ),
                      ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        padding: EdgeInsets.symmetric(
                          vertical: 5,
                          horizontal: 5,
                        ),
                        itemCount: provider.leadsList.length,
                        itemBuilder: (context, index) {
                          String accname = provider.leadsList[index].aname ?? "";
                          RegExp regex =
                          RegExp(provider.searchController.text, caseSensitive: false);
                          Iterable<Match> matches =
                          regex.allMatches(accname);

                          List<TextSpan> textSpans = [];
                          int previousMatchEnd = 0;

                          for (Match match in matches) {
                            if (match.start > previousMatchEnd) {
                              // Add non-matching text before this match
                              textSpans.add(
                                TextSpan(
                                  text: accname.substring(
                                      previousMatchEnd, match.start),
                                  style: TextStyle(
                                    color: AppColors.semi_black,
                                    fontSize: 12,
                                    fontFamily: "JakartaMedium",
                                  ),
                                ),
                              );
                            }

                            // Add the matching text with highlighting
                            textSpans.add(
                              TextSpan(
                                text: accname.substring(
                                    match.start, match.end),
                                style: TextStyle(
                                  color: AppColors.app_blue,
                                  fontSize: 12, // Highlight color
                                  fontFamily: "JakartaMedium",
                                ),
                              ),
                            );

                            previousMatchEnd = match.end;
                          }

                          // Add any remaining non-matching text after the last match
                          if (previousMatchEnd < accname.length) {
                            textSpans.add(
                              TextSpan(
                                text: accname.substring(previousMatchEnd),
                                style: TextStyle(
                                  color: AppColors.semi_black,
                                  fontSize: 12,
                                  fontFamily: "JakartaMedium",
                                ),
                              ),
                            );
                          }
                          return InkResponse(
                            onTap: () {
                              Navigator.pushAndRemoveUntil(
                                context,
                                MaterialPageRoute(
                                  builder:
                                      (context) => ProspectDetailsByMode(
                                        pageTitleName: "Lead Details",
                                        mode: "Executive",
                                        leadId: provider.leadsList[index].lid,
                                      ),
                                  settings: RouteSettings(
                                    name: 'ProspectDetails',
                                  ),
                                ),
                                (Route<dynamic> route) =>
                                    route.settings.name == 'CrmdashboardScreen',
                              );
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(14),
                              ),

                              margin: EdgeInsets.only(
                                bottom: 5,
                                left: 5,
                                right: 5,
                                top: 5,
                              ),
                              padding: EdgeInsets.only(
                                bottom:
                                    MediaQuery.of(context).viewInsets.bottom,
                              ),
                              child: ListTile(
                                leading: SvgPicture.asset(
                                  "assets/svg/crm/crm_search_list_ic.svg",
                                ),
                                title: RichText(text: TextSpan(
                                  children: textSpans,
                                  style:  TextStyle(
                                    color: AppColors.semi_black,
                                    fontSize: 12, // Highlight color
                                    fontFamily: "JakartaMedium",
                                  ),
                                )),
                                // trailing: SvgPicture.asset(
                                //   "assets/svg/arrow_right_new.svg",
                                // ),
                              ),
                            ),
                          );
                        },
                      ),
                    ],
                    if (provider.enquiresList.length > 0) ...[
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Padding(
                          padding: EdgeInsets.symmetric(horizontal: 10),
                          child: Text(
                            "Enquiries",
                            style: TextStyle(
                              fontSize: 16,
                              color: AppColors.grey_thick,
                            ),
                          ),
                        ),
                      ),
                      ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        padding: EdgeInsets.symmetric(
                          vertical: 5,
                          horizontal: 5,
                        ),
                        itemCount: provider.enquiresList.length,
                        itemBuilder: (context, index) {
                          String accname = "";
                          if(provider.enquiresList[index].companyName!.isEmpty){
                            accname = provider.enquiresList[index].name ?? "";
                          }else{
                            accname = provider.enquiresList[index].companyName ?? "";
                          }


                          RegExp regex =
                          RegExp(provider.searchController.text, caseSensitive: false);
                          Iterable<Match> matches =
                          regex.allMatches(accname);

                          List<TextSpan> textSpans = [];
                          int previousMatchEnd = 0;

                          for (Match match in matches) {
                            if (match.start > previousMatchEnd) {
                              // Add non-matching text before this match
                              textSpans.add(
                                TextSpan(
                                  text: accname.substring(
                                      previousMatchEnd, match.start),
                                  style: TextStyle(
                                    color: AppColors.semi_black,
                                    fontSize: 12,
                                    fontFamily: "JakartaMedium",
                                  ),
                                ),
                              );
                            }

                            // Add the matching text with highlighting
                            textSpans.add(
                              TextSpan(
                                text: accname.substring(
                                    match.start, match.end),
                                style: TextStyle(
                                  color: AppColors.app_blue,
                                  fontSize: 12, // Highlight color
                                  fontFamily: "JakartaMedium",
                                ),
                              ),
                            );

                            previousMatchEnd = match.end;
                          }

                          // Add any remaining non-matching text after the last match
                          if (previousMatchEnd < accname.length) {
                            textSpans.add(
                              TextSpan(
                                text: accname.substring(previousMatchEnd),
                                style: TextStyle(
                                  color: AppColors.semi_black,
                                  fontSize: 12,
                                  fontFamily: "JakartaMedium",
                                ),
                              ),
                            );
                          }
                          return Container(
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(14),
                            ),

                            margin: EdgeInsets.only(
                              bottom: 5,
                              left: 5,
                              right: 5,
                              top: 5,
                            ),
                            padding: EdgeInsets.only(
                              bottom: MediaQuery.of(context).viewInsets.bottom,
                            ),
                            child: ListTile(
                              leading: SvgPicture.asset(
                                  "assets/svg/crm/crm_search_list_ic.svg",
                              ),
                              // title: Text(
                              //   provider.enquiresList[index].companyName == ""
                              //       ? provider.enquiresList[index].name!
                              //       : provider.enquiresList[index].companyName!,
                              //   style: TextStyle(
                              //     fontFamily: "JakartaMedium",
                              //     fontSize: 14,
                              //   ),
                              // ),
                              title:RichText(text: TextSpan(
                                children: textSpans,
                                style:  TextStyle(
                                  color: AppColors.semi_black,
                                  fontSize: 12, // Highlight color
                                  fontFamily: "JakartaMedium",
                                ),
                              )),
                              // trailing: SvgPicture.asset(
                              //   "assets/svg/arrow_right_new.svg",
                              // ),
                            ),
                          );
                        },
                      ),
                    ],
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
