import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:generp/Notifiers/crmProvider/addProspectLeadsProvider.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/Utils/dropdownTheme.dart';
import 'package:provider/provider.dart';
import '../../Models/crmModels/crmProspectDetailsAddLeadsResponse.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';

class AddProspectLeads extends StatefulWidget {
  final String leadID;
  final String mode;

  const AddProspectLeads({super.key, required this.leadID, required this.mode});

  @override
  State<AddProspectLeads> createState() => _AddProspectLeadsState();
}

class _AddProspectLeadsState extends State<AddProspectLeads> {
  Dropdowntheme ddtheme = Dropdowntheme();

  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;
  @override
  void initState() {
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      final provider = Provider.of<Addprospectleadsprovider>(
        context,
        listen: false,
      );
      await provider.crmProspectDetailsAddLeadsViewAPIFunction(
        context,
        widget.mode,
      );

      // Initialize controllers and dropdowns after API call
      provider.initializeForm(context);
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _connectivity.disposeStream();
  }

  @override
  Widget build(BuildContext context) {
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.mobile:
        connection = 'Online';
        break;
      case ConnectivityResult.wifi:
        connection = 'Online';
        break;
      case ConnectivityResult.none:
      default:
        connection = 'Offline';
    }
    return (connection == "Online")
        ? Platform.isAndroid
            ? WillPopScope(
              onWillPop: () => onBackPressed(context),
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(BuildContext context) {
    return Consumer<Addprospectleadsprovider>(
      builder: (context, editProvider, child) {
        return Scaffold(
          resizeToAvoidBottomInset: true,
          backgroundColor: AppColors.white,
          appBar: appbar2(
            context,
            "Add Lead",
            editProvider.resetForm,
            const SizedBox(width: 0),
          ),
          body: Container(
            padding: const EdgeInsets.symmetric(horizontal: 10),
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  TextWidget(context, "Employee"),
                  DropdownButtonHideUnderline(
                    child: Row(
                      children: [
                        Expanded(
                          child: DropdownButton2<LeadEmployees>(
                            hint: Text(
                              "Select Source",
                              style: TextStyle(fontSize: 14),
                            ),
                            items:
                                editProvider.employeeList
                                    .map(
                                      (slist) => DropdownMenuItem<LeadEmployees>(
                                        value: slist,
                                        child: Text(
                                          slist.name!,
                                          style: TextStyle(fontSize: 14),
                                        ),
                                      ),
                                    )
                                    .toList(),
                            value:
                                editProvider.employeeList.contains(
                                      editProvider.selectedEmployee,
                                    )
                                    ? editProvider.selectedEmployee
                                    : null,

                            // value: provider.selectedEmployees,
                            onChanged: (LeadEmployees? value) {
                              if (value != null) {
                                if (editProvider.employeeList.isNotEmpty) {
                                  editProvider.selectedEmployee = value;
                                  editProvider.selectedEmployeeId = value!.id!;
                                  editProvider.selectedEmployeeValue =
                                      value!.name!;
                                }
                              }
                            },
                            isExpanded: true,
                            dropdownSearchData: DropdownSearchData(
                              searchInnerWidgetHeight: 50,
                              searchController: editProvider.searchController,
                              searchInnerWidget: Padding(
                                padding: const EdgeInsets.all(8),
                                child: TextFormField(
                                  controller: editProvider.searchController,
                                  decoration: InputDecoration(
                                    isDense: true,
                                    contentPadding: const EdgeInsets.symmetric(
                                      horizontal: 10,
                                      vertical: 8,
                                    ),
                                    hintText: 'Search account...',
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                  ),
                                ),
                              ),
                              searchMatchFn: (item, searchValue) {
                                return item.value?.name?.toLowerCase().contains(
                                      searchValue.toLowerCase(),
                                    ) ??
                                    false;
                              },
                            ),
                            onMenuStateChange: (isOpen) {
                              if (!isOpen) {
                                editProvider.searchController.clear();
                              }
                            },
                            buttonStyleData: ddtheme.buttonStyleData,
                            iconStyleData: ddtheme.iconStyleData,
                            menuItemStyleData: ddtheme.menuItemStyleData,
                            dropdownStyleData: ddtheme.dropdownStyleData,
                          ),
                        ),
                      ],
                    ),
                  ),

                  InkResponse(
                    onTap: () {
                      editProvider.editAddNewRow();
                    },
                    child: Container(
                      margin: const EdgeInsets.symmetric(vertical: 10),
                      height: 45,
                      width: MediaQuery.of(context).size.width,
                      decoration: BoxDecoration(
                        color: const Color(0xFFE6F6FF),
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(
                          color: AppColors.app_blue,
                          width: 0.5,
                        ),
                      ),
                      child: Center(
                        child: Text(
                          "+ Add Product",
                          style: TextStyle(
                            fontFamily: "JakartaMedium",
                            color: AppColors.app_blue,
                          ),
                        ),
                      ),
                    ),
                  ),
                  if (editProvider.leadProductsList.isNotEmpty ||
                      editProvider.editProductPriceControllers.isNotEmpty) ...[
                    ListView.builder(
                      itemCount:
                          editProvider.editProductPriceControllers.length,
                      physics: const NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemBuilder: (context, j) {
                        return Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 10,
                          ),
                          margin: const EdgeInsets.symmetric(vertical: 10),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(20),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              TextWidget(context, "Product"),
                              DropdownButtonHideUnderline(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: DropdownButton2<Products>(
                                        isExpanded: true,
                                        hint: const Text(
                                          'Select Product',
                                          style: TextStyle(fontSize: 14),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                        items:
                                            editProvider.leadProductsList
                                                .map(
                                                  (ord) => DropdownMenuItem<
                                                    Products
                                                  >(
                                                    value: ord,
                                                    child: Text(
                                                      "(Product Name: ${ord.name})",
                                                      style: const TextStyle(
                                                        fontSize: 14,
                                                      ),
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                    ),
                                                  ),
                                                )
                                                .toList(),
                                        value:
                                            editProvider.selectedProductIds[j] !=
                                                    null
                                                ? editProvider.leadProductsList
                                                    .firstWhere(
                                                      (ord) =>
                                                          ord.id ==
                                                          editProvider
                                                              .selectedProductIds[j],
                                                      orElse:
                                                          () =>
                                                              editProvider
                                                                  .leadProductsList[0],
                                                    )
                                                : null,
                                        onChanged: (Products? value) {
                                          if (value != null) {
                                            editProvider
                                                .updateSelectedProductIds(
                                                  j,
                                                  value,
                                                );
                                            editProvider.selectedProductIds[j] =
                                                value.id?.toString() ?? '';
                                            editProvider.updateTotalAmount(j);
                                          }
                                        },
                                        buttonStyleData:
                                            ddtheme.buttonStyleData,
                                        iconStyleData: ddtheme.iconStyleData,
                                        menuItemStyleData:
                                            ddtheme.menuItemStyleData,
                                        dropdownStyleData:
                                            ddtheme.dropdownStyleData,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(height: 10),
                              Row(
                                children: [
                                  Expanded(
                                    flex: 2,
                                    child: textControllerWidget(
                                      context,
                                      editProvider
                                          .editProductPriceControllers[j],
                                      "Product Price",
                                      "Enter Product Price",
                                      (value) =>
                                          editProvider.updateTotalAmount(j),
                                      TextInputType.number,
                                      false,
                                      FilteringTextInputFormatter.digitsOnly,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 10),
                              Row(
                                children: [
                                  Expanded(
                                    flex: 2,
                                    child: textControllerWidget(
                                      context,
                                      editProvider.editQuantityControllers[j],
                                      "Quantity",
                                      "Enter Quantity",
                                      (value) =>
                                          editProvider.updateTotalAmount(j),
                                      TextInputType.number,
                                      false,
                                      FilteringTextInputFormatter.digitsOnly,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 10),
                              Row(
                                children: [
                                  Expanded(
                                    flex: 2,
                                    child: textControllerWidget(
                                      context,
                                      editProvider
                                          .editTotalAmountControllers[j],
                                      "Total Amount",
                                      "Enter Total Amount",
                                      (_) {},
                                      TextInputType.number,
                                      true,
                                      FilteringTextInputFormatter.digitsOnly,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  ],
                  TextWidget(context, "Status"),
                  DropdownButtonHideUnderline(
                    child: Row(
                      children: [
                        Expanded(
                          child: DropdownButton2<String>(
                            hint: Text(
                              "Select Status",
                              style: TextStyle(fontSize: 14),
                            ),
                            items:
                                editProvider.statusList
                                    .map(
                                      (slist) => DropdownMenuItem<String>(
                                        value: slist,
                                        child: Text(
                                          slist,
                                          style: TextStyle(fontSize: 14),
                                        ),
                                      ),
                                    )
                                    .toList(),
                            value: editProvider.selectedStatus,
                            onChanged: (String? value) {
                              if (value != null) {
                                if (editProvider.statusList.isNotEmpty) {
                                  editProvider.selectedStatus = value;
                                }
                              }
                            },
                            isExpanded: true,
                            buttonStyleData: ddtheme.buttonStyleData,
                            iconStyleData: ddtheme.iconStyleData,
                            menuItemStyleData: ddtheme.menuItemStyleData,
                            dropdownStyleData: ddtheme.dropdownStyleData,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          floatingActionButtonLocation:
              FloatingActionButtonLocation.centerFloat,
          bottomNavigationBar: InkResponse(
            onTap:
                editProvider.submitLoading
                    ? null
                    : () {
                      editProvider.submitForm(
                        context,
                        widget.mode,
                        widget.leadID,
                        editProvider.selectedEmployeeId,
                        editProvider.selectedStatus,
                      );
                      // editProvider.crmProspectDetailsAddLeadsSubmitAPIFunction(context, mode, account_id, acc_manager_id, products, lead_status)
                    },
            child: Container(
              height: 45,
              alignment: Alignment.center,
              margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 15),
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
              decoration: BoxDecoration(
                color: AppColors.app_blue,
                borderRadius: BorderRadius.circular(15),
              ),
              child:
                  editProvider.submitLoading
                      ? CircularProgressIndicator.adaptive(
                        valueColor: AlwaysStoppedAnimation<Color>(
                          AppColors.app_blue,
                        ),
                      )
                      : const Text(
                        "Submit",
                        style: TextStyle(
                          fontSize: 15,
                          fontFamily: "JakartaMedium",
                          color: Colors.white,
                        ),
                      ),
            ),
          ),
        );
      },
    );
  }
}
