import 'dart:io';

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/Models/commonModels/DistrictsResponse.dart';
import 'package:generp/Models/commonModels/SubLocationsResponse.dart';
import 'package:generp/Utils/dropdownTheme.dart';
import 'package:generp/screens/notifierExports.dart';
import 'package:provider/provider.dart';

import '../../Models/ordersModels/AddOrderViewResponse.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:generp/Utils/commonServices.dart';

class AddorderScreen extends StatefulWidget {
  final pageTitleName;
  final mode;

  const AddorderScreen({super.key, this.pageTitleName, this.mode});

  @override
  State<AddorderScreen> createState() => _AddorderScreenState();
}

class _AddorderScreenState extends State<AddorderScreen> {
  FocusNode focusNode = FocusNode();
  FocusNode focusNodetpc = FocusNode();
  List<FocusNode> focusNodes = List.generate(10, (index) => FocusNode());
  Dropdowntheme ddtheme = Dropdowntheme();

  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var provider = Provider.of<Addorderprovider>(context, listen: false);
      if (provider.dateNow == null) {
        provider.setDate(DateTime.now());
      }
      provider.getLocationPermission(context);
      provider.getCurrentLocation();
      provider.ordersAddOrderAPIViewFunction(context, widget.mode);
    });
  }

  @override
  void dispose() {
    focusNodes.map((e) => e.dispose());
    focusNode.dispose();
    focusNodetpc.dispose();
    _connectivity.disposeStream();

    super.dispose();
  }

  Future<bool> _onBackPressed(BuildContext context) async {
    Navigator.pop(context, true);
    return true;
  }

  @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"
        ? Consumer<Addorderprovider>(
          builder: (context, provider, child) {
            return WillPopScope(
              child: SafeArea(
                top: false,
                bottom: Platform.isIOS ? false : true,
                child: Scaffold(
                  resizeToAvoidBottomInset: true,
                  backgroundColor: AppColors.white,
                  appBar: appbar2(
                    context,
                    "${widget.pageTitleName}",
                    provider.resetForm,
                    SizedBox(width: 0),
                  ),
                  body: Container(
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          TextWidget(context, "Account"),
                          InkResponse(
                            onTap: () {
                              if (focusNode.hasFocus) {
                                focusNode.unfocus();
                              } else {
                                FocusScope.of(context).requestFocus(focusNode);
                              }
                            },
                            child: Container(
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                color: AppColors.text_field_color,
                                borderRadius: BorderRadius.circular(14),
                              ),
                              child: ListTile(
                                onTap: () {
                                  if (focusNode.hasFocus) {
                                    focusNode.unfocus();
                                  } else {
                                    FocusScope.of(
                                      context,
                                    ).requestFocus(focusNode);
                                  }
                                },
                                title: TextFormField(
                                  focusNode: focusNode,
                                  onTapUpOutside: (event) {
                                    focusNode.unfocus();
                                  },
                                  controller: provider.dropDownSearchController,
                                  onChanged: (value) async {
                                    Future.delayed(
                                      Duration(milliseconds: 100),
                                      () async {
                                        await provider
                                            .ordersAddOrderSelectAccountAPIFunction(
                                              context,
                                              widget.mode,
                                              provider.selectedAccountID,
                                              value,
                                            );
                                      },
                                    );
                                  },
                                  decoration: InputDecoration(
                                    enabledBorder: InputBorder.none,
                                    focusedBorder: InputBorder.none,
                                    isDense: true,
                                    contentPadding: const EdgeInsets.symmetric(
                                      horizontal: 0,
                                      vertical: 8,
                                    ),

                                    hintText: 'Select Account Type',
                                    hintStyle: const TextStyle(fontSize: 14),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                  ),
                                ),

                                trailing: InkResponse(
                                  onTap: () {
                                    if (focusNode.hasFocus) {
                                      focusNode.unfocus();
                                    } else {
                                      FocusScope.of(
                                        context,
                                      ).requestFocus(focusNode);
                                    }
                                  },
                                  child: SvgPicture.asset(
                                    "assets/svg/arrow_dropdown.svg",
                                    height: 25,
                                    width: 20,
                                  ),
                                ),
                              ),
                            ),
                          ),
                          if (provider.accountList.isNotEmpty &&
                              focusNode.hasFocus) ...[
                            Card(
                              margin: EdgeInsets.symmetric(horizontal: 0),
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 10),
                                height: widget.mode == "self" ? 50 : 150,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(16),
                                ),
                                child: Scrollbar(
                                  thickness: 2.5,
                                  radius: Radius.circular(6),
                                  thumbVisibility: true,
                                  child: ListView.builder(
                                    itemCount: provider.accountList.length,
                                    shrinkWrap: true,
                                    physics: AlwaysScrollableScrollPhysics(),
                                    itemBuilder: (context, index) {
                                      return InkResponse(
                                        onTap: () async {
                                          if (provider.accountList.isNotEmpty) {
                                            provider.selectedAccountList =
                                                provider.accountList[index];

                                            print(
                                              "Selected Complaint Type: ${provider.accountList[index].text}, ID: ${provider.accountList[index].id}",
                                            );
                                            provider.selectedAccountID =
                                                provider.accountList[index].id!;
                                            provider.selectedAccountName =
                                                provider
                                                    .accountList[index]
                                                    .text!;
                                            print(
                                              "hfjkshfg" +
                                                  provider.selectedAccountID
                                                      .toString(),
                                            );
                                            provider
                                                .dropDownSearchController
                                                .text = provider
                                                    .accountList[index]
                                                    .text!;
                                            provider
                                                .ordersAddOrderAccountDetailsAPIFunction(
                                                  context,
                                                  provider.selectedAccountID,
                                                );
                                          }
                                          // provider.ordersAddPaymentSelectOrderAPIFunction(context, provider.selectedAccountID);
                                          provider.accountList = [];
                                        },
                                        child: SizedBox(
                                          height: 45,
                                          child: Align(
                                            alignment: Alignment.centerLeft,
                                            child: Text(
                                              provider.accountList[index].text!,
                                            ),
                                          ),
                                        ),
                                      );
                                    },
                                  ),
                                ),
                              ),
                            ),
                          ],
                          errorWidget(context, provider.selectAccountError),
                          if (widget.mode == "admin") ...[
                            TextWidget(context, "Sales Person"),
                            DropdownButtonHideUnderline(
                              child: Row(
                                children: [
                                  Expanded(
                                    child: DropdownButton2<Employees>(
                                      isExpanded: true,
                                      hint: Text(
                                        "Select Sales Person",
                                        style: TextStyle(fontSize: 14),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                      items:
                                          provider.employees
                                              .map(
                                                (e) =>
                                                    DropdownMenuItem<Employees>(
                                                      value: e,
                                                      child: Text(
                                                        e.name!,
                                                        style: const TextStyle(
                                                          fontSize: 14,
                                                        ),
                                                      ),
                                                    ),
                                              )
                                              .toList(),
                                      value: provider.selectedEmployees,
                                      onChanged: (Employees? value) {
                                        if (provider.employees.isNotEmpty) {
                                          provider.selectedEmployees = value;
                                          provider.selectedEmployeeID =
                                              value!.id!;
                                          provider.selectedEmployeeName =
                                              value!.name!;
                                        }
                                      },
                                      buttonStyleData: ddtheme.buttonStyleData,
                                      iconStyleData: ddtheme.iconStyleData,
                                      menuItemStyleData:
                                          ddtheme.menuItemStyleData,
                                      dropdownStyleData:
                                          ddtheme.dropdownStyleData,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                          TextWidget(context, "Order Received Date"),
                          GestureDetector(
                            onTap: () {
                              provider.showDatePickerDialog(context);
                            },
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Expanded(
                                  child: Container(
                                    height: 50,
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                      color: AppColors.text_field_color,
                                      borderRadius: BorderRadius.circular(14),
                                    ),
                                    child: Padding(
                                      padding: const EdgeInsets.fromLTRB(
                                        10.0,
                                        0.0,
                                        10,
                                        0,
                                      ),
                                      child: TextFormField(
                                        controller:
                                            provider
                                                .orderReceivedDateController,
                                        keyboardType: TextInputType.text,
                                        enabled: false,
                                        maxLines: 1,
                                        readOnly: true,
                                        onChanged: (value) {},
                                        decoration: InputDecoration(
                                          hintText: "Enter Date",
                                          hintStyle: TextStyle(
                                            fontWeight: FontWeight.w400,
                                            color: Color(0xFFB4BEC0),
                                            fontSize: 14,
                                          ),

                                          enabledBorder: InputBorder.none,
                                          disabledBorder: InputBorder.none,
                                          focusedBorder: InputBorder.none,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(context, provider.orderDateError),

                          textControllerWidget(
                            context,
                            provider.billingNameController,
                            "Billing Name",
                            "Enter Billing Name",
                            provider.onChangedBillingName,
                            TextInputType.text,
                            false,
                            null,
                            focusNodes[0],
                            null,
                            TextInputAction.done,
                          ),
                          errorWidget(context, provider.billingNameError),
                          TextWidget(context, "Billing State"),
                          //dd
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<States>(
                                    isExpanded: true,
                                    hint: Text(
                                      "Select State",
                                      style: TextStyle(fontSize: 14),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    items:
                                        provider.billingStates
                                            .map(
                                              (e) => DropdownMenuItem<States>(
                                                value: e,
                                                child: Text(
                                                  e.name!,
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                ),
                                              ),
                                            )
                                            .toList(),
                                    value: provider.selecetdBillingStates,
                                    onChanged: (States? value) {
                                      if (provider.billingStates.isNotEmpty) {
                                        provider.selecetdBillingStates = value;
                                        provider.selectedBillingStateID =
                                            value!.id!;
                                        provider.selectedBillingStateName =
                                            value!.name!;
                                        if (provider
                                            .billingDistricts
                                            .isNotEmpty) {
                                          provider.billingDistricts.clear();
                                          // provider.selectedBillingDistricts=null;
                                          provider.selectedBillingDistrictId =
                                              null;
                                          provider.selectedBillingDistrictValue =
                                              "";
                                        }

                                        provider.getDistrictAPI(
                                          context,
                                          provider.selectedBillingStateID,
                                        );
                                      }
                                    },
                                    dropdownSearchData: DropdownSearchData(
                                      searchInnerWidgetHeight: 50,
                                      searchController:
                                          provider.billingStateSearchController,
                                      searchInnerWidget: Padding(
                                        padding: const EdgeInsets.all(8),
                                        child: TextFormField(
                                          controller:
                                              provider
                                                  .billingStateSearchController,
                                          decoration: InputDecoration(
                                            isDense: true,
                                            contentPadding:
                                                const EdgeInsets.symmetric(
                                                  horizontal: 10,
                                                  vertical: 8,
                                                ),
                                            hintText: 'Search Sate...',
                                            border: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                            ),
                                          ),
                                        ),
                                      ),
                                      searchMatchFn: (item, searchValue) {
                                        return item.value?.name
                                                ?.toLowerCase()
                                                .contains(
                                                  searchValue.toLowerCase(),
                                                ) ??
                                            false;
                                      },
                                    ),
                                    onMenuStateChange: (isOpen) {
                                      if (!isOpen) {
                                        provider.billingStateSearchController
                                            .clear();
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(
                            context,
                            provider.selectedBillingStateError,
                          ),
                          TextWidget(context, "Billing District"),
                          //dd
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<Districts>(
                                    isExpanded: true,
                                    hint: Text(
                                      "Select District",
                                      style: const TextStyle(fontSize: 14),
                                    ),
                                    items:
                                        provider.billingDistricts
                                            .map(
                                              (e) =>
                                                  DropdownMenuItem<Districts>(
                                                    value: e,
                                                    child: Text(
                                                      e.district!,
                                                      style: const TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                    ),
                                                  ),
                                            )
                                            .toList(),
                                    value: provider.selectedBillingDistricts,
                                    onChanged: (Districts? value) {
                                      if (provider
                                          .billingDistricts
                                          .isNotEmpty) {
                                        provider.selectedBillingDistricts =
                                            value;
                                        provider.selectedBillingDistrictId =
                                            value!.id!;
                                        provider.selectedBillingDistrictValue =
                                            value!.district!;
                                        if (provider
                                            .billingSubLocations
                                            .isNotEmpty) {
                                          provider.billingSubLocations.clear();
                                          // provider.selectedBillingSubLocations = null;
                                          provider.selectedBillingSubLocID =
                                              null;
                                          provider.selectedBillingSubLocValue =
                                              "";
                                        }
                                        provider.getSubLocationAPI(
                                          context,
                                          provider.selectedBillingDistrictId,
                                        );
                                      }
                                    },
                                    dropdownSearchData: DropdownSearchData(
                                      searchInnerWidgetHeight: 50,
                                      searchController:
                                          provider
                                              .billingDistrictSearchController,
                                      searchInnerWidget: Padding(
                                        padding: const EdgeInsets.all(8),
                                        child: TextFormField(
                                          controller:
                                              provider
                                                  .billingDistrictSearchController,
                                          decoration: InputDecoration(
                                            isDense: true,
                                            contentPadding:
                                                const EdgeInsets.symmetric(
                                                  horizontal: 10,
                                                  vertical: 8,
                                                ),
                                            hintText: 'Search District...',
                                            border: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                            ),
                                          ),
                                        ),
                                      ),
                                      searchMatchFn: (item, searchValue) {
                                        return item.value?.district
                                                ?.toLowerCase()
                                                .contains(
                                                  searchValue.toLowerCase(),
                                                ) ??
                                            false;
                                      },
                                    ),
                                    onMenuStateChange: (isOpen) {
                                      if (!isOpen) {
                                        provider.billingDistrictSearchController
                                            .clear();
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(
                            context,
                            provider.selectedBillingDistrictError,
                          ),
                          TextWidget(context, "Billing Sub Location"),
                          //dd
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<SubLocations>(
                                    hint: Text(
                                      "Select Sub Locality",
                                      style: const TextStyle(fontSize: 14),
                                    ),
                                    items:
                                        provider.billingSubLocations
                                            .map(
                                              (e) => DropdownMenuItem<
                                                SubLocations
                                              >(
                                                value: e,
                                                child: Text(
                                                  e.subLocality!,
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                ),
                                              ),
                                            )
                                            .toList(),
                                    value: provider.selectedBillingSubLocations,
                                    onChanged: (SubLocations? value) {
                                      if (provider
                                          .billingSubLocations
                                          .isNotEmpty) {
                                        provider.selectedBillingSubLocations =
                                            value;
                                        provider.selectedBillingSubLocID =
                                            value!.id!;
                                        provider.selectedBillingSubLocValue =
                                            value!.subLocality!;
                                      }
                                    },
                                    dropdownSearchData: DropdownSearchData(
                                      searchInnerWidgetHeight: 50,
                                      searchController:
                                          provider
                                              .billingSubLocSearchController,
                                      searchInnerWidget: Padding(
                                        padding: const EdgeInsets.all(8),
                                        child: TextFormField(
                                          controller:
                                              provider
                                                  .billingSubLocSearchController,
                                          decoration: InputDecoration(
                                            isDense: true,
                                            contentPadding:
                                                const EdgeInsets.symmetric(
                                                  horizontal: 10,
                                                  vertical: 8,
                                                ),
                                            hintText: 'Search Sub Location...',
                                            border: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                            ),
                                          ),
                                        ),
                                      ),
                                      searchMatchFn: (item, searchValue) {
                                        return item.value?.subLocality
                                                ?.toLowerCase()
                                                .contains(
                                                  searchValue.toLowerCase(),
                                                ) ??
                                            false;
                                      },
                                    ),
                                    onMenuStateChange: (isOpen) {
                                      if (!isOpen) {
                                        provider.billingSubLocSearchController
                                            .clear();
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(
                            context,
                            provider.selectedBillingSubLocError,
                          ),
                          textControllerWidget(
                            context,
                            provider.billingAddressController,
                            "Billing Address",
                            "Enter Billing Address",
                            provider.onChangedBillingAddress,
                            TextInputType.text,
                            false,
                            null,
                            focusNodes[1],
                            focusNodes[2],
                            TextInputAction.next,
                          ),
                          errorWidget(context, provider.billingAddressError),

                          textControllerWidget(
                            context,
                            provider.billingPincodeController,
                            "Billing Pin code",
                            "Enter Billing Pin code",
                            provider.onChangedBillingPincode,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                            focusNodes[2],
                            null,
                            TextInputAction.done,
                            6,
                          ),
                          errorWidget(context, provider.billingPincodeError),

                          TextWidget(context, "Dispatch State"),
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<States>(
                                    isExpanded: true,
                                    hint: Text(
                                      "Select State",
                                      style: TextStyle(fontSize: 14),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    items:
                                        provider.dispatchStates
                                            .map(
                                              (e) => DropdownMenuItem<States>(
                                                value: e,
                                                child: Text(
                                                  e.name!,
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                ),
                                              ),
                                            )
                                            .toList(),
                                    value: provider.selecetdDispatchStates,
                                    onChanged: (States? value) {
                                      if (provider.dispatchStates.isNotEmpty) {
                                        provider.selecetdDispatchStates = value;
                                        provider.selectedDispatchStateID =
                                            value!.id!;
                                        provider.selectedDispatchStateName =
                                            value!.name!;
                                        if (provider
                                            .dispatchDistricts
                                            .isNotEmpty) {
                                          provider.dispatchDistricts.clear();
                                          // provider.selectedDispatchDistricts = null;
                                          provider.selectedDispatchDistrictId =
                                              null;
                                          provider.selectedDispatchDistrictValue =
                                              "";
                                        }
                                        provider.getDispatchDistrictAPI(
                                          context,
                                          provider.selectedDispatchStateID,
                                        );
                                      }
                                    },
                                    dropdownSearchData: DropdownSearchData(
                                      searchInnerWidgetHeight: 50,
                                      searchController:
                                          provider
                                              .dispatchStateSearchController,
                                      searchInnerWidget: Padding(
                                        padding: const EdgeInsets.all(8),
                                        child: TextFormField(
                                          controller:
                                              provider
                                                  .dispatchStateSearchController,
                                          decoration: InputDecoration(
                                            isDense: true,
                                            contentPadding:
                                                const EdgeInsets.symmetric(
                                                  horizontal: 10,
                                                  vertical: 8,
                                                ),
                                            hintText: 'Search Sate...',
                                            border: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                            ),
                                          ),
                                        ),
                                      ),
                                      searchMatchFn: (item, searchValue) {
                                        return item.value?.name
                                                ?.toLowerCase()
                                                .contains(
                                                  searchValue.toLowerCase(),
                                                ) ??
                                            false;
                                      },
                                    ),
                                    onMenuStateChange: (isOpen) {
                                      if (!isOpen) {
                                        provider.dispatchStateSearchController
                                            .clear();
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(
                            context,
                            provider.selectedDispatchStateError,
                          ),
                          //dd
                          TextWidget(context, "Dispatch District"),
                          //dd
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<Districts>(
                                    isExpanded: true,
                                    hint: Text(
                                      "Select District",
                                      style: const TextStyle(fontSize: 14),
                                    ),
                                    items:
                                        provider.dispatchDistricts
                                            .map(
                                              (e) =>
                                                  DropdownMenuItem<Districts>(
                                                    value: e,
                                                    child: Text(
                                                      e.district!,
                                                      style: const TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                    ),
                                                  ),
                                            )
                                            .toList(),
                                    value: provider.selectedDispatchDistricts,
                                    onChanged: (Districts? value) {
                                      if (provider
                                          .dispatchDistricts
                                          .isNotEmpty) {
                                        provider.selectedDispatchDistricts =
                                            value;
                                        provider.selectedDispatchDistrictId =
                                            value!.id!;
                                        provider.selectedDispatchDistrictValue =
                                            value!.district!;
                                        if (provider
                                            .dispatchSubLocations
                                            .isNotEmpty) {
                                          provider.dispatchSubLocations.clear();
                                          // provider.selectedDispatchSubLocations=null;
                                          provider.selectedDispatchSubLocID =
                                              null;
                                          provider.selectedDispatchSubLocValue =
                                              "";
                                        }
                                        provider.getDispatchSubLocationAPI(
                                          context,
                                          provider.selectedDispatchDistrictId,
                                        );
                                      }
                                    },
                                    dropdownSearchData: DropdownSearchData(
                                      searchInnerWidgetHeight: 50,
                                      searchController:
                                          provider
                                              .dispatchDistrictSearchController,
                                      searchInnerWidget: Padding(
                                        padding: const EdgeInsets.all(8),
                                        child: TextFormField(
                                          controller:
                                              provider
                                                  .dispatchDistrictSearchController,
                                          decoration: InputDecoration(
                                            isDense: true,
                                            contentPadding:
                                                const EdgeInsets.symmetric(
                                                  horizontal: 10,
                                                  vertical: 8,
                                                ),
                                            hintText: 'Search District...',
                                            border: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                            ),
                                          ),
                                        ),
                                      ),
                                      searchMatchFn: (item, searchValue) {
                                        return item.value?.district
                                                ?.toLowerCase()
                                                .contains(
                                                  searchValue.toLowerCase(),
                                                ) ??
                                            false;
                                      },
                                    ),
                                    onMenuStateChange: (isOpen) {
                                      if (!isOpen) {
                                        provider
                                            .dispatchDistrictSearchController
                                            .clear();
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(
                            context,
                            provider.selectedDispatchDistrictError,
                          ),
                          TextWidget(context, "Dispatch Sub Location"),
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<SubLocations>(
                                    hint: Text(
                                      "Select Sub Locality",
                                      style: const TextStyle(fontSize: 14),
                                    ),
                                    items:
                                        provider.dispatchSubLocations
                                            .map(
                                              (e) => DropdownMenuItem<
                                                SubLocations
                                              >(
                                                value: e,
                                                child: Text(
                                                  e.subLocality!,
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                ),
                                              ),
                                            )
                                            .toList(),
                                    value:
                                        provider.selectedDispatchSubLocations,
                                    onChanged: (SubLocations? value) {
                                      if (provider
                                          .dispatchSubLocations
                                          .isNotEmpty) {
                                        provider.selectedDispatchSubLocations =
                                            value;
                                        provider.selectedDispatchSubLocID =
                                            value!.id!;
                                        provider.selectedDispatchSubLocValue =
                                            value!.subLocality!;
                                      }
                                    },
                                    dropdownSearchData: DropdownSearchData(
                                      searchInnerWidgetHeight: 50,
                                      searchController:
                                          provider
                                              .dispatchSubLocSearchController,
                                      searchInnerWidget: Padding(
                                        padding: const EdgeInsets.all(8),
                                        child: TextFormField(
                                          controller:
                                              provider
                                                  .dispatchSubLocSearchController,
                                          decoration: InputDecoration(
                                            isDense: true,
                                            contentPadding:
                                                const EdgeInsets.symmetric(
                                                  horizontal: 10,
                                                  vertical: 8,
                                                ),
                                            hintText: 'Search Sub Location...',
                                            border: OutlineInputBorder(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                            ),
                                          ),
                                        ),
                                      ),
                                      searchMatchFn: (item, searchValue) {
                                        return item.value?.subLocality
                                                ?.toLowerCase()
                                                .contains(
                                                  searchValue.toLowerCase(),
                                                ) ??
                                            false;
                                      },
                                    ),
                                    onMenuStateChange: (isOpen) {
                                      if (!isOpen) {
                                        provider.dispatchSubLocSearchController
                                            .clear();
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(
                            context,
                            provider.selectedDispatchSubLocError,
                          ),
                          //dd
                          textControllerWidget(
                            context,
                            provider.dispatchAddressController,
                            "Dispatch Address",
                            "Enter Dispatch Address",
                            provider.onChangedDispatchAddress,
                            TextInputType.text,
                            false,
                            null,
                            focusNodes[3],
                            focusNodes[4],
                            TextInputAction.next,
                          ),
                          errorWidget(context, provider.dispatchAddressError),

                          textControllerWidget(
                            context,
                            provider.dispatchPincodeController,
                            "Dispatch Pin code",
                            "Enter Dispatch Pin code",
                            provider.onChangedDispatchPincode,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                            focusNodes[4],
                            focusNodes[5],
                            TextInputAction.next,
                            6,
                          ),
                          errorWidget(context, provider.dispatchPincodeError),

                          textControllerWidget(
                            context,
                            provider.gstController,
                            "GST Number",
                            "Enter GST Number",
                            provider.onChangedGst,
                            TextInputType.text,
                            false,
                            null,
                            focusNodes[5],
                            null,
                            TextInputAction.done,
                          ),
                          errorWidget(context, provider.gstError),

                          InkResponse(
                            onTap: () {
                              _showAttachmentSheet(context);
                            },
                            child: Container(
                              margin: EdgeInsets.symmetric(vertical: 10),
                              height: 45,
                              width: MediaQuery.of(context).size.width,
                              decoration: BoxDecoration(
                                color: Color(0xFFE6F6FF),
                                borderRadius: BorderRadius.circular(12),
                                border: Border.all(
                                  color: AppColors.app_blue,
                                  width: 0.5,
                                ),
                              ),
                              child: Center(
                                child: Text(
                                  "Upload Purchase Order",
                                  style: TextStyle(
                                    fontFamily: "JakartaMedium",
                                    color: AppColors.app_blue,
                                  ),
                                ),
                              ),
                            ),
                          ),
                          if (provider.imagePicked == 1 &&
                              provider.imagePath != null) ...[
                            Padding(
                              padding: const EdgeInsets.symmetric(
                                vertical: 4.0,
                              ),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    "${provider.imagePath}",
                                    style: TextStyle(
                                      color: AppColors.semi_black,
                                      fontSize: 11,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  InkResponse(
                                    onTap: () {
                                      provider.imagePicked = 0;
                                      provider.imagePath = null;
                                      provider.imageFilePath = null;
                                    },
                                    child: SvgPicture.asset(
                                      "assets/svg/ic_close.svg",
                                      width: 15,
                                      height: 15,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],

                          TextWidget(context, "Unloading Scope"),
                          //dd
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<String>(
                                    hint: Text(
                                      "Select Unloading Scope",
                                      style: const TextStyle(fontSize: 14),
                                    ),
                                    items:
                                        provider.unloadingScope
                                            .map(
                                              (e) => DropdownMenuItem<String>(
                                                value: e!,
                                                child: Text(
                                                  e,
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                ),
                                              ),
                                            )
                                            .toList(),
                                    value: provider.selectedUnloadingScope,
                                    onChanged: (String? value) {
                                      if (provider.unloadingScope.isNotEmpty) {
                                        provider.selectedUnloadingScope = value;
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          TextWidget(context, "Freight Scope"),
                          //dd
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<String>(
                                    hint: Text(
                                      "Select Freight Scope",
                                      style: const TextStyle(fontSize: 14),
                                    ),
                                    items:
                                        provider.freightScope
                                            .map(
                                              (e) => DropdownMenuItem<String>(
                                                value: e!,
                                                child: Text(
                                                  e,
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                ),
                                              ),
                                            )
                                            .toList(),
                                    value: provider.selectedFreightScope,
                                    onChanged: (String? value) {
                                      if (provider.freightScope.isNotEmpty) {
                                        provider.selectedFreightScope = value;
                                      }
                                    },
                                    buttonStyleData: ButtonStyleData(
                                      height: 50,
                                      width: 160,
                                      padding: const EdgeInsets.only(
                                        left: 14,
                                        right: 14,
                                      ),
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(14),
                                        color: AppColors.text_field_color,
                                      ),
                                    ),
                                    iconStyleData: IconStyleData(
                                      icon: SvgPicture.asset(
                                        "assets/svg/arrow_dropdown.svg",
                                        height: 25,
                                        width: 20,
                                      ),
                                      iconSize: 12,
                                      iconEnabledColor: Color(0xFF2D2D2D),
                                      iconDisabledColor: Colors.grey,
                                    ),
                                    dropdownStyleData: DropdownStyleData(
                                      maxHeight: 200,
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(14),
                                        color: AppColors.text_field_color,
                                      ),
                                      scrollbarTheme: ScrollbarThemeData(
                                        radius: const Radius.circular(15),
                                        thickness:
                                            MaterialStateProperty.all<double>(
                                              6,
                                            ),
                                        thumbVisibility:
                                            MaterialStateProperty.all<bool>(
                                              true,
                                            ),
                                      ),
                                    ),
                                    menuItemStyleData: const MenuItemStyleData(
                                      height: 40,
                                      padding: EdgeInsets.only(
                                        left: 14,
                                        right: 14,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          TextWidget(context, "Erection Scope"),
                          //dd
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<String>(
                                    hint: Text(
                                      "Select Erection Scope",
                                      style: const TextStyle(fontSize: 14),
                                    ),
                                    items:
                                        provider.erectionScope
                                            .map(
                                              (e) => DropdownMenuItem<String>(
                                                value: e!,
                                                child: Text(
                                                  e,
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                ),
                                              ),
                                            )
                                            .toList(),
                                    value: provider.selectedErectionScope,
                                    onChanged: (String? value) {
                                      if (provider.erectionScope.isNotEmpty) {
                                        provider.selectedErectionScope = value;
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          TextWidget(context, "TPC Applicable"),
                          //dd
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<String>(
                                    hint: Text(
                                      "TPC Applicable",
                                      style: const TextStyle(fontSize: 14),
                                    ),
                                    items:
                                        provider.tpcApplicable
                                            .map(
                                              (e) => DropdownMenuItem<String>(
                                                value: e!,
                                                child: Text(
                                                  e,
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                ),
                                              ),
                                            )
                                            .toList(),
                                    value: provider.selectedTpcStatus,
                                    onChanged: (String? value) {
                                      if (provider.tpcApplicable.isNotEmpty) {
                                        provider.selectedTpcStatus = value;
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),

                          if (provider.selectedTpcStatus == "Yes") ...[
                            TextWidget(context, "TPC Agent"),

                            //dd
                            Container(
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                color: AppColors.text_field_color,
                                borderRadius: BorderRadius.circular(14),
                              ),
                              child: ListTile(
                                title: TextFormField(
                                  focusNode: focusNodetpc,
                                  onTapUpOutside: (event) {
                                    focusNodetpc.unfocus();
                                  },
                                  controller:
                                      provider.dropDownTpcSearchController,
                                  onChanged: (value) async {
                                    Future.delayed(
                                      Duration(milliseconds: 100),
                                      () async {
                                        await provider
                                            .ordersAddOrderTPCAgentFunction(
                                              context,
                                              widget.mode,
                                              value,
                                            );
                                      },
                                    );
                                  },
                                  decoration: InputDecoration(
                                    enabledBorder: InputBorder.none,
                                    focusedBorder: InputBorder.none,
                                    isDense: true,
                                    contentPadding: const EdgeInsets.symmetric(
                                      horizontal: 0,
                                      vertical: 8,
                                    ),
                                    hintText: 'Select TPC Agent',
                                    hintStyle: const TextStyle(fontSize: 14),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                  ),
                                ),

                                trailing: InkResponse(
                                  onTap: () {
                                    if (focusNodetpc.hasFocus) {
                                      focusNodetpc.unfocus();
                                    } else {
                                      FocusScope.of(
                                        context,
                                      ).requestFocus(focusNodetpc);
                                    }
                                  },
                                  child: SvgPicture.asset(
                                    "assets/svg/arrow_dropdown.svg",
                                    height: 25,
                                    width: 20,
                                  ),
                                ),
                              ),
                            ),
                            if (provider.tpcAgent.isNotEmpty &&
                                focusNodetpc.hasFocus) ...[
                              Card(
                                margin: EdgeInsets.symmetric(horizontal: 0),
                                child: Container(
                                  padding: EdgeInsets.symmetric(horizontal: 10),
                                  height: 150,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(16),
                                  ),
                                  child: Scrollbar(
                                    thickness: 2.5,
                                    radius: Radius.circular(6),
                                    thumbVisibility: true,
                                    child: ListView.builder(
                                      itemCount: provider.tpcAgent.length,
                                      shrinkWrap: true,
                                      physics: AlwaysScrollableScrollPhysics(),
                                      itemBuilder: (context, index) {
                                        return InkResponse(
                                          onTap: () async {
                                            if (provider.tpcAgent.isNotEmpty) {
                                              provider.selectedTpcAgent =
                                                  provider.tpcAgent[index];

                                              print(
                                                "Selected Complaint Type: ${provider.tpcAgent[index].text}, ID: ${provider.tpcAgent[index].id}",
                                              );
                                              provider.selectedTpcAgentID =
                                                  provider.tpcAgent[index].id!;
                                              provider.selectedTpcAgentValue =
                                                  provider
                                                      .tpcAgent[index]
                                                      .text!;
                                              print(
                                                "hfjkshfg" +
                                                    provider.selectedTpcAgentID
                                                        .toString(),
                                              );
                                              provider
                                                  .dropDownTpcSearchController
                                                  .text = provider
                                                      .tpcAgent[index]
                                                      .text!;
                                            }
                                            // provider.ordersAddPaymentSelectOrderAPIFunction(context, provider.selectedAccountID);
                                            // provider.tpcAgent = [];
                                          },
                                          child: SizedBox(
                                            height: 45,
                                            child: Align(
                                              alignment: Alignment.centerLeft,
                                              child: Text(
                                                provider.tpcAgent[index].text!,
                                              ),
                                            ),
                                          ),
                                        );
                                      },
                                    ),
                                  ),
                                ),
                              ),
                            ],

                            textControllerWidget(
                              context,
                              provider.tpcAmountController,
                              "TPC Amount",
                              "Enter TPC Amount",
                              provider.onChangeTpcAmount,
                              TextInputType.number,
                              false,
                              FilteringTextInputFormatter.digitsOnly,
                              focusNodes[6],
                              focusNodes[7],
                              TextInputAction.next,
                            ),
                            errorWidget(context, provider.tpcAmountError),
                          ],

                          ///Addorderbutton
                          OrderForm(),
                          //dd
                        ],
                      ),
                    ),
                  ),
                  floatingActionButtonLocation:
                      FloatingActionButtonLocation.centerFloat,
                  bottomNavigationBar: InkResponse(
                    onTap:
                        provider.submitClicked
                            ? null
                            : () {
                              provider.submitClicked = true;
                              var order_prod_data = provider.getFormData();
                              print(order_prod_data);
                              print(order_prod_data['orders']);

                              ///[{"product_id":"1","qty":"1","price":"500","cgst_p":"9","sgst_p":"9","igst_p":"0","total_price":"500"},
                              ///{"product_id":"2","qty":"1","price":"1000","cgst_p":"9","sgst_p":"9","igst_p":"0","total_price":"1000"}]
                              provider.getCurrentLocation();
                              provider.ordersAddOrderAPISubmitFunction(
                                context,
                                widget.mode,
                                provider.selectedEmployeeID,
                                provider.selectedAccountID,
                                provider.selectedDispatchDistrictId,
                                provider.selectedDispatchSubLocID,
                                provider.selectedUnloadingScope,
                                provider.selectedFreightScope,
                                provider.selectedErectionScope,
                                provider.selectedTpcStatus,
                                provider.selectedTpcStatus,
                                provider.selectedBillingStateID,
                                provider.selectedBillingDistrictId,
                                provider.selectedBillingSubLocID,
                                provider.selectedTpcAgentID,
                                order_prod_data['orders'],
                              );
                            },
                    child: Container(
                      height: 45,
                      alignment: Alignment.center,
                      margin: EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 15,
                      ),
                      padding: EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 5,
                      ),
                      decoration: BoxDecoration(
                        color: AppColors.app_blue,
                        borderRadius: BorderRadius.circular(15),
                      ),
                      child:
                          provider.submitClicked
                              ? CircularProgressIndicator.adaptive(
                                valueColor: AlwaysStoppedAnimation<Color>(
                                  AppColors.white,
                                ),
                              )
                              : Text(
                                "Submit",
                                style: TextStyle(
                                  fontSize: 15,
                                  fontFamily: "JakartaMedium",
                                  color: Colors.white,
                                ),
                              ),
                    ),
                  ),
                ),
              ),
              onWillPop: () async {
                provider.resetForm();
                return _onBackPressed(context);
              },
            );
          },
        )
        : NoNetwork(context);
  }

  Future<void> _showAttachmentSheet(BuildContext context) {
    return showModalBottomSheet(
      useSafeArea: true,
      isDismissible: true,
      isScrollControlled: true,
      showDragHandle: true,
      backgroundColor: Colors.white,
      enableDrag: true,
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return SafeArea(
              child: Consumer<Addorderprovider>(
                builder: (context, provider, child) {
                  return Padding(
                    padding: EdgeInsets.only(
                      bottom:
                          MediaQuery.of(
                            context,
                          ).viewInsets.bottom, // This handles keyboard
                    ),
                    child: Container(
                      margin: EdgeInsets.only(
                        bottom: 15,
                        left: 15,
                        right: 15,
                        top: 10,
                      ),

                      child: SingleChildScrollView(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Align(
                              alignment: Alignment.center,
                              child: Text(
                                "Select Source",
                                style: TextStyle(
                                  color: AppColors.app_blue,
                                  fontFamily: "JakrtaMedium",
                                  fontSize: 16,
                                ),
                              ),
                            ),
                            SizedBox(height: 15),
                            InkWell(
                              onTap: () {
                                Navigator.of(context).pop(false);
                                provider.imgFromGallery(context);
                              },
                              child: Container(
                                height: 35,
                                child: Text("Select photo from gallery"),
                              ),
                            ),
                            SizedBox(height: 10),
                            InkWell(
                              onTap: () {
                                Navigator.of(context).pop(false);
                                provider.imgFromCamera(context);
                              },
                              child: Container(
                                height: 35,
                                child: Text("Capture photo from camera"),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}

class OrderForm extends StatelessWidget {
  OrderForm({super.key});

  FocusNode focusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<Addorderprovider>(context);
    Dropdowntheme ddtheme = Dropdowntheme();
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
      ),
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 10),
            // Add Product Button
            InkWell(
              onTap: provider.addNewRow,
              child: Container(
                margin: const EdgeInsets.symmetric(vertical: 10),
                height: 45,
                width: double.infinity,
                decoration: BoxDecoration(
                  color: const Color(0xFFE6F6FF),
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(color: Colors.blue, width: 0.5),
                ),
                child: const Center(
                  child: Text(
                    "+ Add Product",
                    style: TextStyle(
                      fontFamily: "JakartaMedium",
                      color: Colors.blue,
                      fontSize: 16,
                    ),
                  ),
                ),
              ),
            ),
            // Product Rows (Horizontal ListView)
            if (provider.ProductControllers.isNotEmpty) ...[
              ListView.builder(
                shrinkWrap: true,
                itemCount: provider.ProductControllers.length,
                itemBuilder: (context, index) {
                  return Container(
                    width: MediaQuery.of(context).size.width,

                    padding: const EdgeInsets.all(5.0),
                    decoration: BoxDecoration(
                      color: const Color(0xFFF5F5F5),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          "Product ${index + 1}",
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 8.0),
                        Container(
                          padding: const EdgeInsets.all(3.0),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // Product Dropdown
                              Row(
                                children: [
                                  Expanded(
                                    child: DropdownButtonHideUnderline(
                                      child: DropdownButton2<SaleProducts>(
                                        isExpanded: true,
                                        hint: Text(
                                          'Select Product',
                                          style: TextStyle(fontSize: 14),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                        items:
                                            provider.saleProducts
                                                .map(
                                                  (ord) => DropdownMenuItem<
                                                    SaleProducts
                                                  >(
                                                    value: ord,
                                                    child: Text(
                                                      "${ord.prodName}" ?? '',
                                                      style: const TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                    ),
                                                  ),
                                                )
                                                .toList(),
                                        value:
                                            provider.selectedSaleProductID[index] !=
                                                    null
                                                ? provider.saleProducts.firstWhere(
                                                  (product) =>
                                                      product.id ==
                                                      provider
                                                          .selectedSaleProductID[index],
                                                )
                                                : null,

                                        onChanged: (SaleProducts? value) {
                                          if (value != null) {
                                            if (provider
                                                .saleProducts
                                                .isNotEmpty) {
                                              provider.selectedSaleProducts =
                                                  value;

                                              provider.updateSelectedProduct(
                                                index,
                                                provider.selectedSaleProducts,
                                              );
                                              // provider.selectedOrderIds = value!.orderId!;
                                              // provider.selectedOrderNumbers = value!.orderNumber!;
                                            }
                                          }
                                        },
                                        buttonStyleData:
                                            ddtheme.buttonStyleData,
                                        iconStyleData: ddtheme.iconStyleData,
                                        menuItemStyleData:
                                            ddtheme.menuItemStyleData,
                                        dropdownStyleData:
                                            ddtheme.dropdownStyleData,
                                      ),
                                    ),
                                  ),
                                ],
                              ),

                              const SizedBox(height: 8.0),
                              Row(
                                children: [
                                  // Price TextField (Read-only)
                                  Expanded(
                                    child: textControllerWidget(
                                      context,
                                      provider.PriceControllers[index],
                                      "Price",
                                      "Enter Price",
                                      (p0) {},
                                      TextInputType.number,
                                      false,
                                      FilteringTextInputFormatter.digitsOnly,
                                      null,
                                      null,
                                      TextInputAction.next,
                                    ),
                                  ),
                                  const SizedBox(width: 8.0),
                                  // Quantity TextField
                                  // Expanded(
                                  //   child: TextField(
                                  //     controller:
                                  //     provider.QuantityControllers[index],
                                  //     decoration: const InputDecoration(
                                  //       labelText: 'Quantity',
                                  //       border: OutlineInputBorder(),
                                  //       isDense: true,
                                  //     ),
                                  //     keyboardType: TextInputType.number,
                                  //     inputFormatters: [
                                  //       FilteringTextInputFormatter.digitsOnly
                                  //     ],
                                  //     onChanged: (value) {
                                  //
                                  //     },
                                  //   ),
                                  // ),
                                  Expanded(
                                    child: textControllerWidget(
                                      context,
                                      provider.QuantityControllers[index],
                                      "Quantity",
                                      "Enter Quantity",
                                      (p0) {
                                        provider.updateRowCalculations(index);
                                      },
                                      TextInputType.number,
                                      false,
                                      FilteringTextInputFormatter.digitsOnly,
                                      null,
                                      null,
                                      TextInputAction.next,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 8.0),
                              Row(
                                children: [
                                  // CGST TextField
                                  // Expanded(
                                  //   child: TextField(
                                  //     controller: provider.CGSTControllers[index],
                                  //     decoration: const InputDecoration(
                                  //       labelText: 'CGST %',
                                  //       border: OutlineInputBorder(),
                                  //       isDense: true,
                                  //     ),
                                  //     keyboardType: TextInputType.number,
                                  //     inputFormatters: [
                                  //       FilteringTextInputFormatter.digitsOnly
                                  //     ],
                                  //     onChanged: (value) {
                                  //       provider.updateRowCalculations(index);
                                  //     },
                                  //   ),
                                  // ),
                                  Expanded(
                                    child: textControllerWidget(
                                      context,
                                      provider.CGSTControllers[index],
                                      "CGST %",
                                      "Enter CGST %",
                                      (p0) {
                                        provider.updateRowCalculations(index);
                                      },
                                      TextInputType.number,
                                      false,
                                      FilteringTextInputFormatter.digitsOnly,
                                      null,
                                      null,
                                      TextInputAction.next,
                                    ),
                                  ),
                                  const SizedBox(width: 8.0),
                                  // SGST TextField
                                  // Expanded(
                                  //   child: TextField(
                                  //     controller: provider.SGSTControllers[index],
                                  //     decoration: const InputDecoration(
                                  //       labelText: 'SGST %',
                                  //       border: OutlineInputBorder(),
                                  //       isDense: true,
                                  //     ),
                                  //     keyboardType: TextInputType.number,
                                  //     inputFormatters: [
                                  //       FilteringTextInputFormatter.digitsOnly
                                  //     ],
                                  //     onChanged: (value) {
                                  //       provider.updateRowCalculations(index);
                                  //     },
                                  //   ),
                                  // ),
                                  Expanded(
                                    child: textControllerWidget(
                                      context,
                                      provider.SGSTControllers[index],
                                      "SGST %",
                                      "Enter SGST %",
                                      (p0) {
                                        provider.updateRowCalculations(index);
                                      },
                                      TextInputType.number,
                                      false,
                                      FilteringTextInputFormatter.digitsOnly,
                                      null,
                                      null,
                                      TextInputAction.next,
                                    ),
                                  ),
                                  const SizedBox(width: 8.0),
                                  // IGST TextField
                                  // Expanded(
                                  //   child: TextField(
                                  //     controller: provider.IGSTControllers[index],
                                  //     decoration: const InputDecoration(
                                  //       labelText: 'IGST %',
                                  //       border: OutlineInputBorder(),
                                  //       isDense: true,
                                  //     ),
                                  //     keyboardType: TextInputType.number,
                                  //     inputFormatters: [
                                  //       FilteringTextInputFormatter.digitsOnly
                                  //     ],
                                  //     onChanged: (value) {
                                  //       provider.updateRowCalculations(index);
                                  //     },
                                  //   ),
                                  // ),
                                  Expanded(
                                    child: textControllerWidget(
                                      context,
                                      provider.IGSTControllers[index],
                                      "IGST %",
                                      "Enter IGST %",
                                      (p0) {
                                        provider.updateRowCalculations(index);
                                      },
                                      TextInputType.number,
                                      false,
                                      FilteringTextInputFormatter.digitsOnly,
                                      null,
                                      null,
                                      TextInputAction.next,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 8.0),
                              Row(
                                children: [
                                  // Total Price TextField (Read-only)
                                  // Expanded(
                                  //   child: TextField(
                                  //     controller:
                                  //     provider.TaxableValueControllers[index],
                                  //     decoration: const InputDecoration(
                                  //       labelText: 'Total Price',
                                  //       border: OutlineInputBorder(),
                                  //       isDense: true,
                                  //     ),
                                  //     keyboardType: TextInputType.number,
                                  //     readOnly: true,
                                  //   ),
                                  // ),
                                  Expanded(
                                    child: textControllerWidget(
                                      context,
                                      provider.TaxableValueControllers[index],
                                      "Total Price",
                                      "Enter Total Price",
                                      (p0) {
                                        provider.updateRowCalculations(index);
                                      },
                                      TextInputType.number,
                                      true,
                                      null,
                                      null,
                                      null,
                                      TextInputAction.next,
                                    ),
                                  ),
                                  // const SizedBox(width: 8.0),
                                  // // Remove Row Button
                                  // IconButton(
                                  //   icon: const Icon(Icons.delete, color: Colors.red),
                                  //   onPressed: () {
                                  //     provider.removeRow(index);
                                  //   },
                                  // ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ],
            const SizedBox(height: 20),

            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Column(
                children: [
                  textControllerWidget(
                    context,
                    provider.basicAmountReadOnlyController,
                    "Basic Amount",
                    "Enter Basic Amount",
                    (p0) {},
                    TextInputType.text,
                    true,
                    FilteringTextInputFormatter.digitsOnly,
                    null,
                    null,
                    TextInputAction.none,
                  ),
                  textControllerWidget(
                    context,
                    provider.cgstReadOnlyController,
                    "CGST Amount",
                    "Enter CGST Amount",
                    (p0) {},
                    TextInputType.text,
                    true,
                    FilteringTextInputFormatter.digitsOnly,
                    null,
                    null,
                    TextInputAction.none,
                  ),
                  textControllerWidget(
                    context,
                    provider.sgstReadOnlyController,
                    "SGST Amount",
                    "Enter SGST Amount",
                    (p0) {},
                    TextInputType.text,
                    true,
                    FilteringTextInputFormatter.digitsOnly,
                    null,
                    null,
                    TextInputAction.none,
                  ),
                  textControllerWidget(
                    context,
                    provider.igstReadOnlyController,
                    "IGST Amount",
                    "Enter IGST Amount",
                    (p0) {},
                    TextInputType.text,
                    true,
                    FilteringTextInputFormatter.digitsOnly,
                    null,
                    null,
                    TextInputAction.none,
                  ),
                  textControllerWidget(
                    context,
                    provider.totalReadOnlyAmountController,
                    "Total Amount",
                    "Enter Total Amount",
                    (p0) {},
                    TextInputType.text,
                    true,
                    FilteringTextInputFormatter.digitsOnly,
                    null,
                    null,
                    TextInputAction.none,
                  ),
                  textControllerWidget(
                    context,
                    provider.noteController,
                    "Note",
                    "Enter Note",
                    (p0) {},
                    TextInputType.text,
                    false,
                    null,
                    focusNode,
                    null,
                    TextInputAction.done,
                  ),
                ],
              ),
            ),
            // Summary Table
            Visibility(
              visible: false,
              child: Table(
                border: TableBorder.all(color: Colors.grey, width: 1),
                columnWidths: const {
                  0: FlexColumnWidth(2),
                  1: FlexColumnWidth(1),
                },
                children: [
                  _buildTableRow(
                    'Basic Amount',
                    provider.basicAmount.toStringAsFixed(2),
                  ),
                  _buildTableRow(
                    'CGST Amount',
                    provider.cgstAmount.toStringAsFixed(2),
                  ),
                  _buildTableRow(
                    'SGST Amount',
                    provider.sgstAmount.toStringAsFixed(2),
                  ),
                  _buildTableRow(
                    'IGST Amount',
                    provider.igstAmount.toStringAsFixed(2),
                  ),
                  _buildTableRow(
                    'Total Amount',
                    provider.totalAmount.toStringAsFixed(2),
                  ),
                  TableRow(
                    children: [
                      const Padding(
                        padding: EdgeInsets.all(8.0),
                        child: Text(
                          'Note',
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          controller: provider.noteController,
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                            hintText: 'Enter note',
                          ),
                          maxLines: null,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            const SizedBox(height: 20),

            // Submit Button
          ],
        ),
      ),
    );
  }

  TableRow _buildTableRow(String label, value) {
    return TableRow(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(
            label,
            style: const TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(value.toString()),
        ),
      ],
    );
  }
}
