import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dotted_line/dotted_line.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/crmProvider/addNewLeadsandProspectsProvider.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:generp/Utils/dropdownTheme.dart';
import 'package:provider/provider.dart';

import '../../Models/crmModels/GetDistrictOnStateResponse.dart';
import '../../Models/crmModels/GetSegmentOnTeamResponse.dart';
import '../../Models/crmModels/GetSourceOnReferenceResponse.dart';
import '../../Models/crmModels/GetSubLocOnDistrictResponse.dart';
import '../../Models/crmModels/crmNewLeadsProspectsViewResponse.dart';
import '../../Utils/custom_snackbar.dart';
import 'LeadDetailsByMode.dart';
import 'addLeadProductScreen.dart';

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

  @override
  State<Addleadsprospectsscreen> createState() =>
      _AddleadsprospectsscreenState();
}

class _AddleadsprospectsscreenState extends State<Addleadsprospectsscreen> {
  Dropdowntheme ddtheme = Dropdowntheme();
  List<FocusNode> focusNodes = List.generate(20, (index) => FocusNode());
  int _currentStep = 0;
  final _formKey = GlobalKey<FormState>();
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;
  // Controllers to store form data
  final _nameController = TextEditingController();
  final _emailController = TextEditingController();
  final _addressController = TextEditingController();

  @override
  void dispose() {
    _nameController.dispose();
    _emailController.dispose();
    _addressController.dispose();
    focusNodes.map((e) => e.dispose());
    super.dispose();
  }

  void _nextStep() {
    if (_formKey.currentState!.validate()) {
      if (_currentStep < 2) {
        setState(() {
          _currentStep += 1;
        });
      } else {
        // Submit form data
        _submitForm();
      }
    }
  }

  void _previousStep() {
    if (_currentStep > 0) {
      setState(() {
        _currentStep -= 1;
      });
    }
  }

  void _submitForm() {
    // Simulate form submission (e.g., print data or send to server)
    print('Form Submitted:');
    print('Name: ${_nameController.text}');
    print('Email: ${_emailController.text}');
    print('Address: ${_addressController.text}');
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Form submitted successfully!')),
    );
  }

  Future<bool> onBackPressed(BuildContext context) async {
    if (_currentStep > 0) {
      _previousStep();
      return false;
    } else {
      return true;
    }
  }

  @override
  void initState() {
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      final provider = Provider.of<Addnewleadsandprospectsprovider>(
        context,
        listen: false,
      );
      provider.resetForm();
      provider.crmAddLeadsView(context);
    });
  }

  @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<Addnewleadsandprospectsprovider>(
      builder: (context, provider, child) {
        return SafeArea(
          top: false,
          bottom: Platform.isIOS ? false : true,
          child: Scaffold(
            resizeToAvoidBottomInset: true,
            backgroundColor: AppColors.scaffold_bg_color,
            appBar: appbar2New(
              context,
              "Add Leads and Prospect",
              provider.resetForm,
              const SizedBox(width: 0),
              0xFFFFFFFF,
            ),
            //
            body: Form(
              key: _formKey,
              child: Stepper(
                margin: EdgeInsets.symmetric(horizontal: 0, vertical: 0),
                type: StepperType.horizontal,
                currentStep: _currentStep,
                onStepContinue: _nextStep,
                onStepCancel: _previousStep,
                onStepTapped: (value) {
                  print(value);
                  // setState(() {
                  //
                  //   if(value==0){
                  //     _currentStep = value;
                  //   }
                  //   if(_currentStep==1 && value==0){
                  //     _currentStep = value;
                  //   }
                  //   if(_currentStep==2 && value == 1){
                  //     _currentStep = value;
                  //   }
                  //   if (value == 1) {
                  //     if(provider.validateStep1()){
                  //       _currentStep = value;
                  //     }
                  //
                  //   } else if (value == 2) {
                  //     if(provider.validateStep2()){
                  //       _currentStep = value;
                  //     }
                  //
                  //   }
                  //   else {
                  //     _currentStep = value;
                  //   }
                  // });
                  setState(() {
                    if (value == 1 && !provider.validateStep1()) {
                      return;
                    }
                    if (value == 2 && !provider.validateStep2()) {
                      return;
                    }
                    if (value < _currentStep) {
                      _currentStep = value;
                    } else if (value > _currentStep) {
                      _currentStep = value;
                    }
                  });
                },
                connectorColor: WidgetStatePropertyAll(AppColors.app_blue),
                stepIconBuilder: (stepIndex, stepState) {
                  return CircleAvatar(
                    radius: 12,
                    backgroundColor:
                        stepIndex <= _currentStep
                            ? AppColors.app_blue
                            : Colors.grey[300],
                  );
                },
                steps: [
                  Step(
                    label: Text("Step 1", style: TextStyle(fontSize: 12)),
                    title: const Text(''),
                    isActive: _currentStep >= 0,
                    content: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 10,
                      ),

                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          TextWidget(context, "Salutation"),
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<String>(
                                    isExpanded: true,
                                    hint: const Row(
                                      children: [
                                        Expanded(
                                          child: Text(
                                            'Select Salutation',
                                            style: TextStyle(fontSize: 14),
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                      ],
                                    ),
                                    items:
                                        provider.salutationList
                                            .map(
                                              (slist) =>
                                                  DropdownMenuItem<String>(
                                                    value: slist,
                                                    child: Text(
                                                      slist ?? '',
                                                      style: const TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                    ),
                                                  ),
                                            )
                                            .toList(),
                                    value: provider.selectedSalutation,
                                    onChanged: (value) {
                                      if (value != null) {
                                        provider.selectedSalutation = value;
                                        provider.salutationError = null;
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(context, provider.salutationError),

                          textControllerWidget(
                            context,
                            provider.companyNameController,
                            "Company Name",
                            "Enter Company Name",
                            provider.onChangeCompanyName,
                            TextInputType.name,
                            false,
                            null,
                            focusNodes[0],
                            focusNodes[1],
                            TextInputAction.next,
                          ),
                          errorWidget(context, provider.companynameError),

                        textControllerWidget(
                          context,
                          provider.contactPersonNameController,
                          "Contact Person Name",
                          "Enter Name",
                              (value) => provider.onChangeContactPersonName(context, value),
                          TextInputType.name,
                          false,
                          null,
                          focusNodes[1],
                          focusNodes[2],
                          TextInputAction.next,
                        ),

                        errorWidget(context, provider.nameError),

                          textControllerWidget(
                            context,
                            provider.mobileController,
                            "Mobile Number",
                            "Enter Mobile Number",
                                (value) => provider.onChangemobile(context, value),
                            TextInputType.phone,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                            focusNodes[2],
                            focusNodes[3],
                            TextInputAction.done,
                            10,
                          ),
                          errorWidget(context, provider.mobileError),

                          textControllerWidget(
                            context,
                            provider.customerMailIdController,
                            "Customer Email Id",
                            "Enter Email Id",
                            provider.onChangemailId,
                            TextInputType.emailAddress,
                            false,
                            null,
                            focusNodes[3],
                            focusNodes[4],
                            TextInputAction.next,
                          ),
                          errorWidget(context, provider.mailIdError),

                          textControllerWidget(
                            context,
                            provider.designationController,
                            "Customer Designation",
                            "Enter Designation",
                            provider.onChangedesignation,
                            TextInputType.text,
                            false,
                            null,
                            focusNodes[4],
                            null,
                            TextInputAction.done,
                          ),
                          errorWidget(context, provider.designationError),
                        ],
                      ),
                    ),
                  ),
                  Step(
                    label: Text("Step 2", style: TextStyle(fontSize: 12)),
                    title: const Text(''),
                    isActive: _currentStep >= 1,
                    content: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 10,
                      ),

                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          textControllerWidget(
                            context,
                            provider.alternateMobileController,
                            "Alternate Mobile Number",
                            "Enter Alternate Mobile Number",
                            provider.onChangeAlternatemobile,
                            TextInputType.phone,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                            focusNodes[5],
                            focusNodes[6],
                            TextInputAction.next,
                            10,
                          ),

                          errorWidget(context, provider.AlternatemobileError),

                          textControllerWidget(
                            context,
                            provider.telephoneController,
                            "Telephone Number",
                            "Enter Telephone Number",
                            provider.onChangeTelephone,
                            TextInputType.phone,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                            focusNodes[6],
                            null,
                            TextInputAction.done,
                          ),
                          errorWidget(context, provider.TelephoneError),
                          TextWidget(context, "Source"),
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<Sources>(
                                    hint: Text(
                                      "Select Source",
                                      style: TextStyle(fontSize: 14),
                                    ),
                                    items:
                                        provider.sourcesList
                                            .map(
                                              (slist) =>
                                                  DropdownMenuItem<Sources>(
                                                    value: slist,
                                                    child: Text(
                                                      slist.name!,
                                                      style: TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                    ),
                                                  ),
                                            )
                                            .toList(),
                                    // value: provider.selectedSources,
                                    value:
                                        provider.sourcesList.isNotEmpty
                                            ? provider.selectedSources != null
                                                ? provider.sourcesList.firstWhere(
                                                  (element) =>
                                                      element.id ==
                                                      provider
                                                          .selectedSourcesId,
                                                  orElse:
                                                      () =>
                                                          provider
                                                              .sourcesList[0],
                                                )
                                                : null
                                            : null,
                                    onChanged: (Sources? value) {
                                      if (value != null) {
                                        if (provider.sourcesList.isNotEmpty) {
                                          provider.selectedSources = value;
                                          provider.selectedSourcesId =
                                              value.id!;
                                          provider.selectedSourcesValue =
                                              value.name!;

                                          if (provider
                                              .referencesList
                                              .isNotEmpty) {
                                            provider.referencesList.clear();
                                            provider.selectedReferenceId = null;
                                            provider.selectedReferenceValue =
                                                null;
                                          }

                                          provider
                                              .crmLeadListSourceOnReferenceAPIFunction(
                                                context,
                                                "",
                                                provider.selectedSourcesId,
                                              );
                                        }
                                      }
                                    },
                                    isExpanded: true,
                                    dropdownSearchData: DropdownSearchData(
                                      searchInnerWidgetHeight: 50,
                                      searchController:
                                          provider.sourceSearchController,
                                      searchInnerWidget: Padding(
                                        padding: const EdgeInsets.all(8),
                                        child: TextFormField(
                                          controller:
                                              provider.sourceSearchController,
                                          decoration: InputDecoration(
                                            isDense: true,
                                            contentPadding:
                                                const EdgeInsets.symmetric(
                                                  horizontal: 10,
                                                  vertical: 8,
                                                ),
                                            hintText: 'Search Source...',
                                            border: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                            ),
                                          ),
                                        ),
                                      ),
                                      searchMatchFn: (item, searchValue) {
                                        return item.value?.name
                                                ?.toLowerCase()
                                                .contains(
                                                  searchValue.toLowerCase(),
                                                ) ??
                                            false;
                                      },
                                    ),
                                    onMenuStateChange: (isOpen) {
                                      if (!isOpen) {
                                        provider.sourceSearchController.clear();
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(context, provider.sourceError),
                          TextWidget(context, "Reference"),
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<References>(
                                    hint: Text(
                                      "Select Reference",
                                      style: TextStyle(fontSize: 14),
                                    ),
                                    items:
                                        provider.referencesList
                                            .map(
                                              (slist) =>
                                                  DropdownMenuItem<References>(
                                                    value: slist,
                                                    child: Text(
                                                      slist.name!,
                                                      style: TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                    ),
                                                  ),
                                            )
                                            .toList(),
                                    // value: provider.selectedReference,
                                    value:
                                        provider.referencesList.isNotEmpty
                                            ? provider.selectedReference != null
                                                ? provider.referencesList.firstWhere(
                                                  (element) =>
                                                      element.id ==
                                                      provider
                                                          .selectedReferenceId,
                                                  orElse:
                                                      () =>
                                                          provider
                                                              .referencesList[0],
                                                )
                                                : null
                                            : null,
                                    onChanged: (References? value) {
                                      if (value != null) {
                                        if (provider
                                            .referencesList
                                            .isNotEmpty) {
                                          provider.selectedReference = value;
                                          provider.selectedReferenceId =
                                              value.id!;
                                          provider.selectedReferenceValue =
                                              value.name!;
                                        }
                                      }
                                    },
                                    isExpanded: true,
                                    dropdownSearchData: DropdownSearchData(
                                      searchInnerWidgetHeight: 50,
                                      searchController:
                                          provider.referenceSearchController,
                                      searchInnerWidget: Padding(
                                        padding: const EdgeInsets.all(8),
                                        child: TextFormField(
                                          controller:
                                              provider
                                                  .referenceSearchController,
                                          decoration: InputDecoration(
                                            isDense: true,
                                            contentPadding:
                                                const EdgeInsets.symmetric(
                                                  horizontal: 10,
                                                  vertical: 8,
                                                ),
                                            hintText: 'Search Reference...',
                                            border: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                            ),
                                          ),
                                        ),
                                      ),
                                      searchMatchFn: (item, searchValue) {
                                        return item.value?.name
                                                ?.toLowerCase()
                                                .contains(
                                                  searchValue.toLowerCase(),
                                                ) ??
                                            false;
                                      },
                                    ),
                                    onMenuStateChange: (isOpen) {
                                      if (!isOpen) {
                                        provider.referenceSearchController
                                            .clear();
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(context, provider.referenceError),
                          TextWidget(context, "Team"),
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<Teams>(
                                    hint: Text(
                                      "Select Team",
                                      style: TextStyle(fontSize: 14),
                                    ),
                                    items:
                                        provider.teamsList
                                            .map(
                                              (slist) =>
                                                  DropdownMenuItem<Teams>(
                                                    value: slist,
                                                    child: Text(
                                                      slist.name!,
                                                      style: TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                    ),
                                                  ),
                                            )
                                            .toList(),
                                    // value: provider.selectedTeams,
                                    value:
                                        provider.teamsList.isNotEmpty
                                            ? provider.selectedTeams != null
                                                ? provider.teamsList.firstWhere(
                                                  (element) =>
                                                      element.id ==
                                                      provider.selectedTeamsId,
                                                  orElse:
                                                      () =>
                                                          provider.teamsList[0],
                                                )
                                                : null
                                            : null,
                                    onChanged: (Teams? value) {
                                      if (value != null) {
                                        if (provider.teamsList.isNotEmpty) {
                                          provider.selectedTeams = value;
                                          provider.selectedTeamsId = value.id!;
                                          provider.selectedTeamsValue =
                                              value.name!;

                                          if (provider
                                              .segmentsList
                                              .isNotEmpty) {
                                            provider.segmentsList.clear();
                                            provider.selectedSegmentId = null;
                                            provider.selectedSegmentValue =
                                                null;
                                          }
                                          provider
                                              .crmLeadListSegmentOnTeamAPIFunction(
                                                context,
                                                "",
                                                provider.selectedTeamsId,
                                              );
                                        }
                                      }
                                    },
                                    isExpanded: true,
                                    dropdownSearchData: DropdownSearchData(
                                      searchInnerWidgetHeight: 50,
                                      searchController:
                                          provider.teamSearchController,
                                      searchInnerWidget: Padding(
                                        padding: const EdgeInsets.all(8),
                                        child: TextFormField(
                                          controller:
                                              provider.teamSearchController,
                                          decoration: InputDecoration(
                                            isDense: true,
                                            contentPadding:
                                                const EdgeInsets.symmetric(
                                                  horizontal: 10,
                                                  vertical: 8,
                                                ),
                                            hintText: 'Search Team...',
                                            border: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                            ),
                                          ),
                                        ),
                                      ),
                                      searchMatchFn: (item, searchValue) {
                                        return item.value?.name
                                                ?.toLowerCase()
                                                .contains(
                                                  searchValue.toLowerCase(),
                                                ) ??
                                            false;
                                      },
                                    ),
                                    onMenuStateChange: (isOpen) {
                                      if (!isOpen) {
                                        provider.teamSearchController.clear();
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(context, provider.teamsError),
                          TextWidget(context, "Segment"),
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<Segments>(
                                    hint: Text(
                                      "Select Segment",
                                      style: TextStyle(fontSize: 14),
                                    ),
                                    items:
                                        provider.segmentsList
                                            .map(
                                              (slist) =>
                                                  DropdownMenuItem<Segments>(
                                                    value: slist,
                                                    child: Text(
                                                      slist.name!,
                                                      style: TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                    ),
                                                  ),
                                            )
                                            .toList(),
                                    // value: provider.selectedSegment,
                                    value:
                                        provider.segmentsList.isNotEmpty
                                            ? provider.selectedSegment != null
                                                ? provider.segmentsList.firstWhere(
                                                  (element) =>
                                                      element.id ==
                                                      provider
                                                          .selectedSegmentId,
                                                  orElse:
                                                      () =>
                                                          provider
                                                              .segmentsList[0],
                                                )
                                                : null
                                            : null,
                                    onChanged: (Segments? value) {
                                      if (value != null) {
                                        if (provider.segmentsList.isNotEmpty) {
                                          provider.selectedSegment = value;
                                          provider.selectedSegmentId =
                                              value.id!;
                                          provider.selectedSegmentValue =
                                              value.name!;
                                        }
                                      }
                                    },
                                    isExpanded: true,
                                    dropdownSearchData: DropdownSearchData(
                                      searchInnerWidgetHeight: 50,
                                      searchController:
                                          provider.segmentSearchController,
                                      searchInnerWidget: Padding(
                                        padding: const EdgeInsets.all(8),
                                        child: TextFormField(
                                          controller:
                                              provider.segmentSearchController,
                                          decoration: InputDecoration(
                                            isDense: true,
                                            contentPadding:
                                                const EdgeInsets.symmetric(
                                                  horizontal: 10,
                                                  vertical: 8,
                                                ),
                                            hintText: 'Search Segment...',
                                            border: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                            ),
                                          ),
                                        ),
                                      ),
                                      searchMatchFn: (item, searchValue) {
                                        return item.value?.name
                                                ?.toLowerCase()
                                                .contains(
                                                  searchValue.toLowerCase(),
                                                ) ??
                                            false;
                                      },
                                    ),
                                    onMenuStateChange: (isOpen) {
                                      if (!isOpen) {
                                        provider.segmentSearchController
                                            .clear();
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(context, provider.segmentsError),
                        ],
                      ),
                    ),
                  ),
                  Step(
                    label: Text("Step 3", style: TextStyle(fontSize: 12)),
                    title: const Text(''),
                    isActive: _currentStep >= 2,
                    content: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 10,
                          ),

                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(16),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              InkResponse(
                                onTap: () async {
                                  var res = await Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder:
                                          (context) =>
                                              Addleadproductscreen(type: "Add"),
                                      settings: RouteSettings(
                                        name: 'Generatequotationaddeditproduct',
                                      ),
                                    ),
                                  );
                                  if (res != null) {
                                    print("result $res");
                                  }
                                },
                                child: Container(
                                  margin: const EdgeInsets.symmetric(
                                    vertical: 10,
                                  ),
                                  height: 45,
                                  width: MediaQuery.of(context).size.width,
                                  decoration: BoxDecoration(
                                    color: const Color(0xFFE6F6FF),
                                    borderRadius: BorderRadius.circular(12),
                                    border: Border.all(
                                      color: AppColors.app_blue,
                                      width: 0.5,
                                    ),
                                  ),
                                  child: Center(
                                    child: Text(
                                      "+ Add Product",
                                      style: TextStyle(
                                        fontFamily: "JakartaMedium",
                                        color: AppColors.app_blue,
                                      ),
                                    ),
                                  ),
                                ),
                              ),

                              if (provider.productRows.isNotEmpty) ...[
                                const SizedBox(height: 10),
                                SizedBox(
                                  height: 125,
                                  child: ListView.builder(
                                    scrollDirection: Axis.horizontal,
                                    itemCount: provider.productRows.length,
                                    itemBuilder: (context, index) {
                                      final product = provider.productRows[index];
                                      final productName = provider.productsList
                                          .firstWhere(
                                            (p) => p.id == product['product_id'],
                                        orElse: () => Products(
                                          id: '',
                                          name: 'Unknown',
                                        ),
                                      )
                                          .name;
                                      final prodPrice = product['price'] ?? '-';
                                      final prodQty = product['qty'] ?? '-';
                                      final totalPrice = product['net_price'] ?? '-';

                                      // FIX: Get the text from TextEditingController, not the controller itself
                                      final remark = product['remarks'] is TextEditingController
                                          ? (product['remarks'] as TextEditingController).text
                                          : product['remarks']?.toString() ?? '';

                                      return InkResponse(
                                        onTap: () async {
                                          var res = await Navigator.push(
                                            context,
                                            MaterialPageRoute(
                                              builder: (context) => Addleadproductscreen(
                                                type: "Edit",
                                                editIndex: index,
                                              ),
                                              settings: RouteSettings(
                                                name: 'Generatequotationaddeditproduct',
                                              ),
                                            ),
                                          );
                                          if (res != null) {
                                            print("result $res");
                                          }
                                        },
                                        child: Container(
                                          width: MediaQuery.of(context).size.width * 0.8,
                                          margin: EdgeInsets.only(
                                            left: index == 0 ? 10 : 5,
                                            right: index == provider.productRows.length - 1 ? 10 : 5,
                                            bottom: 5,
                                          ),
                                          padding: EdgeInsets.symmetric(
                                            horizontal: 10,
                                            vertical: 8,
                                          ),
                                          decoration: BoxDecoration(
                                            color: Color(0xFFE6F6FF),
                                            borderRadius: BorderRadius.circular(14),
                                          ),
                                          child: Row(
                                            mainAxisAlignment: MainAxisAlignment.start,
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Expanded(
                                                flex: 1,
                                                child: SvgPicture.asset(
                                                  "assets/svg/crm/product_details_ic.svg",
                                                ),
                                              ),
                                              SizedBox(width: 10),
                                              Expanded(
                                                flex: 6,
                                                child: Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  mainAxisAlignment: MainAxisAlignment.start,
                                                  children: [
                                                    Row(
                                                      children: [
                                                        Expanded(
                                                          flex: 4,
                                                          child: Text(
                                                            productName ?? "-",
                                                            maxLines: 2,
                                                            overflow: TextOverflow.ellipsis,
                                                            style: TextStyle(
                                                              fontFamily: "JakartaMedium",
                                                              fontSize: 14,
                                                              color: AppColors.semi_black,
                                                            ),
                                                          ),
                                                        ),
                                                        Expanded(
                                                          flex: 3,
                                                          child: Text(
                                                            textAlign: TextAlign.right,
                                                            "₹$prodPrice",
                                                            style: TextStyle(
                                                              fontFamily: "JakartaMedium",
                                                              fontSize: 14,
                                                              color: AppColors.semi_black,
                                                            ),
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                    Text(
                                                      "x $prodQty",
                                                      style: TextStyle(
                                                        fontFamily: "JakartaMedium",
                                                        fontSize: 14,
                                                        color: AppColors.grey_semi,
                                                      ),
                                                    ),
                                                    SizedBox(height: 5),
                                                    DottedLine(
                                                      dashGapLength: 4,
                                                      dashGapColor: Colors.white,
                                                      dashColor: AppColors.grey_semi,
                                                      dashLength: 2,
                                                      lineThickness: 0.5,
                                                    ),
                                                    SizedBox(height: 5),
                                                    Row(
                                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                      children: [
                                                        Text(
                                                          "₹$totalPrice",
                                                          style: TextStyle(
                                                            fontFamily: "JakartaMedium",
                                                            fontSize: 14,
                                                            color: AppColors.semi_black,
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                    SizedBox(height: 5),
                                                    Row(
                                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                      children: [
                                                        Expanded(
                                                          child: Text(
                                                            remark, // Now this is a String, not a TextEditingController
                                                            style: TextStyle(
                                                              fontFamily: "JakartaMedium",
                                                              fontSize: 14,
                                                              color: AppColors.semi_black,
                                                            ),
                                                            maxLines: 1,
                                                            overflow: TextOverflow.ellipsis,
                                                          ),
                                                        ),
                                                      ],
                                                    )
                                                  ],
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      );
                                    },
                                  ),
                                ),
                              ],

                              if (provider.productRows.isEmpty) ...[
                                if (provider.productsEmptyError != null) ...[
                                  errorWidget(
                                    context,
                                    provider.productsEmptyError,
                                  ),
                                ],
                              ],
                            ],
                          ),
                        ),
                        SizedBox(height: 10),
                        Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 10,
                          ),

                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(16),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              TextWidget(context, "State"),
                              DropdownButtonHideUnderline(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: DropdownButton2<States>(
                                        hint: Text(
                                          "Select State",
                                          style: TextStyle(fontSize: 14),
                                        ),
                                        items:
                                            provider.statesList
                                                .map(
                                                  (slist) =>
                                                      DropdownMenuItem<States>(
                                                        value: slist,
                                                        child: Text(
                                                          slist.name!,
                                                          style: TextStyle(
                                                            fontSize: 14,
                                                          ),
                                                        ),
                                                      ),
                                                )
                                                .toList(),

                                        // value: provider.selectedStates,
                                        value:
                                            provider.statesList.isNotEmpty
                                                ? provider.selectedStates !=
                                                        null
                                                    ? provider.statesList.firstWhere(
                                                      (ord) =>
                                                          ord.id ==
                                                          provider
                                                              .selectedStatesId,
                                                      orElse:
                                                          () =>
                                                              provider
                                                                  .statesList[0],
                                                    )
                                                    : null
                                                : null,
                                        onChanged: (States? value) {
                                          if (value != null) {
                                            if (provider
                                                .statesList
                                                .isNotEmpty) {
                                              provider.selectedStates = value;
                                              provider.selectedStatesId =
                                                  value.id!;
                                              provider.selectedStatesValue =
                                                  value.name!;
                                              provider
                                                  .crmLeadListDistrictsOnStateAPIFunction(
                                                    context,
                                                    "",
                                                    value.id!,
                                                  );
                                              if (provider
                                                  .districtsList
                                                  .isNotEmpty) {
                                                provider.districtsList.clear();
                                                provider.subLocationsList
                                                    .clear();
                                                // provider.selectedDistricts = null;
                                                provider.selectedDistrictId =
                                                    null;
                                                provider.selectedDistrictValue =
                                                    "";

                                                provider.selectedSubLocationId =
                                                    null;
                                                provider.selectedSubLocationValue =
                                                    "";
                                              }
                                            }
                                          }
                                        },
                                        isExpanded: true,
                                        buttonStyleData:
                                            ddtheme.buttonStyleData,
                                        iconStyleData: ddtheme.iconStyleData,
                                        menuItemStyleData:
                                            ddtheme.menuItemStyleData,
                                        dropdownStyleData:
                                            ddtheme.dropdownStyleData,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              errorWidget(context, provider.statesError),
                              TextWidget(context, "District"),
                              DropdownButtonHideUnderline(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: DropdownButton2<Districts>(
                                        hint: Text(
                                          "Select District",
                                          style: TextStyle(fontSize: 14),
                                        ),
                                        items:
                                            provider.districtsList
                                                .map(
                                                  (slist) => DropdownMenuItem<
                                                    Districts
                                                  >(
                                                    value: slist,
                                                    child: Text(
                                                      slist.district!,
                                                      style: TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                    ),
                                                  ),
                                                )
                                                .toList(),

                                        // value: provider.selectedDistricts,
                                        value:
                                            provider.districtsList.isNotEmpty
                                                ? provider.selectedDistricts !=
                                                        null
                                                    ? provider.districtsList.firstWhere(
                                                      (ord) =>
                                                          ord.id ==
                                                          provider
                                                              .selectedDistrictId,
                                                      orElse:
                                                          () =>
                                                              provider
                                                                  .districtsList[0],
                                                    )
                                                    : null
                                                : null,
                                        onChanged: (Districts? value) {
                                          if (value != null) {
                                            if (provider
                                                .districtsList
                                                .isNotEmpty) {
                                              provider.selectedDistricts =
                                                  value;
                                              provider.selectedDistrictId =
                                                  value.id!;
                                              provider.selectedDistrictValue =
                                                  value.district!;
                                              provider
                                                  .crmLeadListSubLocOnDistrictAPIFunction(
                                                    context,
                                                    "",
                                                    value.id!,
                                                  );
                                              if (provider
                                                  .subLocationsList
                                                  .isNotEmpty) {
                                                provider.subLocationsList
                                                    .clear();
                                                // provider.selectedSubLocations =
                                                //     null;
                                                provider.selectedSubLocationId =
                                                    null;
                                                provider.selectedSubLocationValue =
                                                    "";
                                              }
                                            }
                                          }
                                        },
                                        isExpanded: true,
                                        buttonStyleData:
                                            ddtheme.buttonStyleData,
                                        iconStyleData: ddtheme.iconStyleData,
                                        menuItemStyleData:
                                            ddtheme.menuItemStyleData,
                                        dropdownStyleData:
                                            ddtheme.dropdownStyleData,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              errorWidget(context, provider.districtsError),
                              TextWidget(context, "Sub Location"),
                              DropdownButtonHideUnderline(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: DropdownButton2<SubLocations>(
                                        hint: Text(
                                          "Select Sub Location",
                                          style: TextStyle(fontSize: 14),
                                        ),
                                        items:
                                            provider.subLocationsList
                                                .map(
                                                  (slist) => DropdownMenuItem<
                                                    SubLocations
                                                  >(
                                                    value: slist,
                                                    child: Text(
                                                      slist.subLocality!,
                                                      style: TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                    ),
                                                  ),
                                                )
                                                .toList(),

                                        // value: provider.selectedSubLocations,
                                        value:
                                            provider.subLocationsList.isNotEmpty
                                                ? provider.selectedSubLocations !=
                                                        null
                                                    ? provider.subLocationsList
                                                        .firstWhere(
                                                          (ord) =>
                                                              ord.id ==
                                                              provider
                                                                  .selectedSubLocationId,
                                                          orElse:
                                                              () =>
                                                                  provider
                                                                      .subLocationsList[0],
                                                        )
                                                    : null
                                                : null,
                                        onChanged: (SubLocations? value) {
                                          if (value != null) {
                                            if (provider
                                                .subLocationsList
                                                .isNotEmpty) {
                                              provider.selectedSubLocations =
                                                  value;
                                              provider.selectedSubLocationId =
                                                  value.id!;
                                              provider.selectedSubLocationValue =
                                                  value.subLocality!;
                                            }
                                          }
                                        },
                                        isExpanded: true,
                                        buttonStyleData:
                                            ddtheme.buttonStyleData,
                                        iconStyleData: ddtheme.iconStyleData,
                                        menuItemStyleData:
                                            ddtheme.menuItemStyleData,
                                        dropdownStyleData:
                                            ddtheme.dropdownStyleData,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              errorWidget(context, provider.subLocError),
                              TextWidget(context, "Lead Status"),
                              DropdownButtonHideUnderline(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: DropdownButton2<String>(
                                        isExpanded: true,
                                        hint: const Row(
                                          children: [
                                            Expanded(
                                              child: Text(
                                                'Select Lead Status',
                                                style: TextStyle(fontSize: 14),
                                                overflow: TextOverflow.ellipsis,
                                              ),
                                            ),
                                          ],
                                        ),
                                        items:
                                            <String>['Cold', 'Hot', 'Warm']
                                                .map(
                                                  (
                                                    value,
                                                  ) => DropdownMenuItem<String>(
                                                    value: value,
                                                    child: Text(
                                                      value ?? '',
                                                      style: const TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                    ),
                                                  ),
                                                )
                                                .toList(),
                                        value: provider.selectedLeadStatus,
                                        onChanged: (String? newValue) {
                                          setState(() {
                                            provider.selectedLeadStatus =
                                                newValue!;
                                          });
                                        },
                                        buttonStyleData:
                                            ddtheme.buttonStyleData,
                                        iconStyleData: ddtheme.iconStyleData,
                                        menuItemStyleData:
                                            ddtheme.menuItemStyleData,
                                        dropdownStyleData:
                                            ddtheme.dropdownStyleData,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              errorWidget(context, provider.leadStatusError),
                              textControllerWidget(
                                context,
                                provider.addressController,
                                "Address",
                                "Enter Address ",
                                provider.onChangeaddress,
                                TextInputType.streetAddress,
                                false,
                                null,
                                focusNodes[7],
                                null,
                                TextInputAction.done,
                              ),
                              errorWidget(context, provider.addressError),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
                controlsBuilder: (context, details) {
                  // return Row(
                  //   children: [
                  //     ElevatedButton(
                  //       onPressed: () {
                  //         setState(() {
                  //           if (_currentStep == 0) {
                  //             _currentStep = 1;
                  //           } else if (_currentStep == 1) {
                  //             _currentStep = 2;
                  //           } else {
                  //             _currentStep = 0;
                  //           }
                  //         });
                  //         details.onStepContinue;
                  //       },
                  //       child: Text(_currentStep == 2 ? 'Submit' : 'Next'),
                  //     ),
                  //     const SizedBox(width: 10),
                  //     if (_currentStep > 0)
                  //       TextButton(
                  //         onPressed: () {
                  //           setState(() {
                  //             if (_currentStep == 2) {
                  //               _currentStep = 1;
                  //             } else if (_currentStep == 1) {
                  //               _currentStep = 0;
                  //             } else {
                  //               _currentStep = 2;
                  //             }
                  //           });
                  //           details.onStepCancel;
                  //         },
                  //         child: const Text('Back'),
                  //       ),
                  //   ],
                  // );
                  return Column(
                    children: [
                      if (_currentStep == 2) ...[
                  InkResponse(
                    onTap: provider.isSubmitting
                        ? null // disable taps while submitting
                        : () {
                      HapticFeedback.selectionClick();
                      if (provider.validateStep3()) {
                        if (provider.productRows.isNotEmpty) {
                          provider.crmAddNewLeadsAndProspectsAPIFunction(
                            context,
                            "",
                            provider.selectedEmployeesId,
                            provider.selectedSalutation,
                            provider.selectedDistrictId,
                            provider.selectedStatesId,
                            provider.selectedSegmentId,
                            provider.selectedSourcesId,
                            provider.selectedReferenceId,
                            provider.selectedReferenceId,
                            provider.selectedSubLocationId,
                            provider.selectedLeadStatus,
                            provider.getJsonEncodedProducts(),
                          );
                        } else {
                          toast(context, "Add min. 1 product");
                        }
                      }

                      details.onStepContinue;
                      },
                    child: Container(
                      height: 45,
                      alignment: Alignment.center,
                      margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                      decoration: BoxDecoration(
                        color: provider.isSubmitting
                            ? Colors.grey.shade400 // disable color
                      : AppColors.app_blue,
                        borderRadius: BorderRadius.circular(15),
                      ),
                      child: provider.isSubmitting
                          ? const SizedBox(
                        height: 22,
                        width: 22,
                        child: CircularProgressIndicator(
                          strokeWidth: 2.3,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      )
                          : const Text(
                        "Submit",
                        style: TextStyle(
                          fontSize: 15,
                          fontFamily: "JakartaMedium",
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                      ] else ...[
                        InkResponse(
                          onTap: () {
                            HapticFeedback.selectionClick();
                            setState(() {
                              if (_currentStep == 0) {
                                if (provider.validateStep1()) {
                                  _currentStep = 1;
                                }
                              } else if (_currentStep == 1) {
                                if (provider.validateStep2()) {
                                  _currentStep = 2;
                                }
                              } else {
                                _currentStep = 0;
                              }
                            });
                            details.onStepContinue;
                          },
                          child: Container(
                            height: 45,
                            alignment: Alignment.center,
                            margin: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 10,
                            ),
                            padding: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 5,
                            ),
                            decoration: BoxDecoration(
                              color: AppColors.app_blue,
                              borderRadius: BorderRadius.circular(15),
                            ),
                            child: Text(
                              "Proceed to Next Step",
                              textAlign: TextAlign.start,
                              style: TextStyle(
                                fontSize: 15,
                                fontFamily: "JakartaMedium",
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ),
                      ],
                      if (_currentStep > 0) ...[
                        TextButton(
                          onPressed: () {
                            setState(() {
                              if (_currentStep == 2) {
                                _currentStep = 1;
                              } else if (_currentStep == 1) {
                                _currentStep = 0;
                              } else {
                                _currentStep = 2;
                              }
                            });
                            details.onStepCancel;
                          },
                          child: Text(
                            'Back',
                            style: TextStyle(
                              color: AppColors.app_blue,
                              fontSize: 14,
                            ),
                          ),
                        ),
                      ],
                    ],
                  );
                },
              ),
            ),
          ),
        );
      },
    );
  }
  void showCustomSnackBar(BuildContext context, String message) {
    final snackBar = SnackBar(
      behavior: SnackBarBehavior.floating,
      backgroundColor: Colors.black87,
      elevation: 6,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      content: Row(
        children: [
          Icon(Icons.info_outline, color: Colors.white),
          SizedBox(width: 12),
          Expanded(
            child: Text(
              message,
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
      duration: Duration(seconds: 3),
    );

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }
}
