import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/PaymentCollectionProvider.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:generp/screens/serviceEngineer/PaymentDetails.dart';
import 'package:provider/provider.dart';

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

  @override
  State<Accountsuggestions> createState() => _AccountsuggestionsState();
}

class _AccountsuggestionsState extends State<Accountsuggestions> {
  final TextEditingController _searchController = TextEditingController();
  FocusNode searchFocusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return Consumer<Paymentcollectionprovider>(
      builder: (context, provider, child) {
        return WillPopScope(
          onWillPop: () => onBackPressed(context),
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS ? false : true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,
              appBar: appbarNew(context, "Accounts", 0xFFFFFFFF),
              backgroundColor: AppColors.scaffold_bg_color,
              body: Container(
                decoration: BoxDecoration(color: Colors.white),
                child: Column(
                  children: [
                    const SizedBox(height: 10),
                    Container(
                      alignment: Alignment.topLeft,
                      padding: EdgeInsets.symmetric(horizontal: 10),
                      child: Text(
                        "Search Account",
                        style: TextStyle(color: Color(0xFF2d2d2d)),
                      ),
                    ),
                    SizedBox(height: 5),
                    Container(
                      height: 48,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        // color: AppColors.text_field_color,
                        borderRadius: BorderRadius.circular(14),
                        // border:
                        //     searchFocusNode.hasFocus
                        //         ? Border.all(
                        //           color: AppColors.app_blue,
                        //           width: 0.5,
                        //         )
                        //         : null,
                      ),
                      //  alignment: Alignment.center,
                      margin: EdgeInsets.only(left: 5.0, right: 5.0),
                      child: Padding(
                        padding: const EdgeInsets.fromLTRB(5.0, 0.0, 15, 0),
                        child: TextField(
                          controller: _searchController,
                          keyboardType: TextInputType.text,
                          focusNode: searchFocusNode,
                          textCapitalization: TextCapitalization.characters,
                          autofocus: true,
                          style: TextStyle(fontSize: 14),
                          onChanged: (value) {
                            if (value.length >= 3) {
                              provider.AccountSuggestionAPI(context, value);
                            }
                          },
                          onTapOutside: (event) {
                            // Handle onTapOutside
                            FocusScope.of(context).unfocus();
                          },
                          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:
                                  _searchController.text.isNotEmpty
                                      ? InkResponse(
                                        onTap: () {
                                          _searchController.clear();
                                          provider.accountList.clear();
                                        },
                                        child: SvgPicture.asset(
                                          "assets/svg/crm/clear_search.svg",
                                        ),
                                      )
                                      : SvgPicture.asset(
                                        "assets/svg/search_ic.svg",
                                      ),
                            ),
                            counterText: "",
                            hintText: "Enter Account Name",
                            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),
                            ),
                          ),
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 5.0, left: 25.0),
                      alignment: Alignment.topLeft,
                      child: Text(
                        "Note: Enter Minimum 3 Characters",
                        style: TextStyle(fontWeight: FontWeight.w300),
                      ),
                    ),

                    Expanded(
                      child: SingleChildScrollView(
                        physics: AlwaysScrollableScrollPhysics(),
                        child: Container(
                          child: ListView.builder(
                            itemCount: provider.accountList.length,

                            padding: const EdgeInsets.all(5),
                            physics: const NeverScrollableScrollPhysics(),
                            shrinkWrap: true,
                            itemBuilder: (context, index) {
                              var accountList = provider.accountList;
                              String accname =
                                  provider.accountList[index].accountName ?? "";
                              RegExp regex = RegExp(
                                _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: 14,
                                        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: 14, // 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: 14,
                                      fontFamily: "JakartaMedium",
                                    ),
                                  ),
                                );
                              }
                              if (accountList!.isNotEmpty) {
                                return InkWell(
                                  onTap: () {
                                    // if(actname == "pendingComplaints"&&status=="Open"){
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder:
                                            (context) => Paymentdetails(
                                              accountName: "Account",
                                              name:
                                                  accountList[index]
                                                      .accountName,
                                              genId: "",
                                              referenceID:
                                                  accountList[index].accountId,
                                            ),
                                      ),
                                    );
                                    // }
                                  },
                                  child: SizedBox(
                                    child: SizedBox(
                                      width:
                                          MediaQuery.of(context).size.width *
                                          0.9,
                                      // padding: EdgeInsets.fromLTRB(0, 5, 0, 10),
                                      // child: Row(
                                      //   children: [
                                      //     Expanded(
                                      //       flex: 1,
                                      //       child: Container(
                                      //         padding: EdgeInsets.symmetric(
                                      //           horizontal: 10,
                                      //           vertical: 10,
                                      //         ),
                                      //         decoration: BoxDecoration(
                                      //           color: Color(0xFFE6F6FF),
                                      //           borderRadius:
                                      //               BorderRadius.circular(8),
                                      //         ),
                                      //         child: SvgPicture.asset(
                                      //           width: 30,
                                      //           height: 30,
                                      //           "assets/svg/se_block_head.svg",
                                      //         ),
                                      //       ),
                                      //     ),
                                      //     SizedBox(width: 10),
                                      //     Expanded(
                                      //       flex: 5,
                                      //       child: Text(
                                      //         "${accountList![index].accountName}",
                                      //         textAlign: TextAlign.start,
                                      //         maxLines: 3,
                                      //         overflow: TextOverflow.ellipsis,
                                      //         style: TextStyle(
                                      //           color: AppColors.semi_black,
                                      //         ),
                                      //       ),
                                      //     ),
                                      //     Expanded(
                                      //       flex: 1,
                                      //       child: SvgPicture.asset(
                                      //         "assets/svg/arrow_right_new.svg",
                                      //       ),
                                      //     ),
                                      //   ],
                                      // ),
                                      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: 14, // Highlight color
                                              fontFamily: "JakartaMedium",
                                            ),
                                          ),
                                        ),
                                        trailing: SvgPicture.asset(
                                          "assets/svg/arrow_right_new.svg",
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              } else {
                                return Expanded(
                                  child: SingleChildScrollView(
                                    physics: AlwaysScrollableScrollPhysics(),
                                    child: Container(
                                      width: double.infinity,
                                      height:
                                          MediaQuery.of(context).size.height,
                                      // Set width to fill parent width
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.only(
                                          topLeft: Radius.circular(30.0),
                                          topRight: Radius.circular(30.0),
                                        ),
                                      ),
                                      padding: EdgeInsets.fromLTRB(
                                        10,
                                        10,
                                        10,
                                        10,
                                      ),
                                      child: Container(
                                        child: Align(
                                          alignment: Alignment.center,
                                          child: Text(
                                            "No Data Available",
                                            style: TextStyle(
                                              fontWeight: FontWeight.bold,
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              }
                            },
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
