import 'dart:io';

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

class Addleadproductscreen extends StatefulWidget {
  final type;
  final int? editIndex;
  const Addleadproductscreen({super.key, this.type, this.editIndex});

  @override
  State<Addleadproductscreen> createState() => _AddleadproductscreenState();
}

class _AddleadproductscreenState extends State<Addleadproductscreen> {
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;
  Dropdowntheme ddtheme = Dropdowntheme();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      final provider = Provider.of<Addnewleadsandprospectsprovider>(
        context,
        listen: false,
      );
      if (widget.type == "Add") {
        provider.selectedProducts = null;
        provider.selectedProductsId = null;
        provider.selectedProductsValue = null;
        provider.addProductPriceController.clear();
        provider.addQuantityController.clear();
        provider.addTotalAmountController.clear();
      } else {
        provider.prefillProductForEdit(widget.editIndex!);
      }

      // provider.addEditInitializeForm(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<Addnewleadsandprospectsprovider>(
      builder: (context, provider, child) {
        return Scaffold(
          resizeToAvoidBottomInset: true,

          appBar: appbarNew(context, "Generate Quotation", 0xFFFFFFFF),
          backgroundColor: AppColors.scaffold_bg_color,
          body: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 10,
                    vertical: 10,
                  ),
                  margin: const EdgeInsets.symmetric(
                    horizontal: 10,
                    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:
                                    provider.productsList
                                        .map(
                                          (ord) => DropdownMenuItem<Products>(
                                            value: ord,
                                            child: Text(
                                              "${ord.name}",
                                              style: const TextStyle(
                                                fontSize: 14,
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                        )
                                        .toList(),
                                // provider.selectedOrderIds[index] != null?
                                // provider
                                //     .orderList
                                //     .firstWhere(
                                //       (product) =>
                                //   product
                                //       .orderId ==
                                //       provider
                                //           .selectedOrderIds[index],
                                // )
                                value:
                                    provider.selectedProducts != null
                                        ? provider.productsList.firstWhere(
                                          (element) =>
                                              element.id ==
                                              provider.selectedProductsId,
                                        )
                                        : null,
                                onChanged: (Products? value) {
                                  if (value != null) {
                                    provider.selectedProducts = value;
                                    provider.selectedProductsId = value.id!;
                                    provider.selectedProductsValue = value.name;
                                  }

                                  provider.crmSelectedProductDetailsApiFunction(
                                    context,
                                    value!.id.toString(),
                                  );
                                },
                                dropdownSearchData: DropdownSearchData(
                                  searchInnerWidgetHeight: 50,
                                  searchController:
                                      provider.productSearchController,
                                  searchInnerWidget: Padding(
                                    padding: const EdgeInsets.all(8),
                                    child: TextFormField(
                                      controller:
                                          provider.productSearchController,
                                      decoration: InputDecoration(
                                        isDense: true,
                                        contentPadding:
                                            const EdgeInsets.symmetric(
                                              horizontal: 10,
                                              vertical: 8,
                                            ),
                                        hintText: 'Search Product...',
                                        border: OutlineInputBorder(
                                          borderRadius: BorderRadius.circular(
                                            8,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                  searchMatchFn: (item, searchValue) {
                                    return item.value?.name
                                            ?.toLowerCase()
                                            .contains(
                                              searchValue.toLowerCase(),
                                            ) ??
                                        false;
                                  },
                                ),
                                onMenuStateChange: (isOpen) {
                                  if (!isOpen) {
                                    provider.productSearchController.clear();
                                  }
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),

                      const SizedBox(height: 10),
                      textControllerWidget(
                        context,
                        provider.addProductPriceController,
                        "Product Price",
                        "Enter Product Price",
                        provider.addEditUpdateTotalAmount,
                        TextInputType.number,
                        false,
                        FilteringTextInputFormatter.digitsOnly,
                      ),
                      const SizedBox(height: 10),
                      textControllerWidget(
                        context,
                        provider.addQuantityController,
                        "Quantity",
                        "Enter Quantity",
                        provider.addEditUpdateTotalAmount,
                        TextInputType.number,
                        false,
                        FilteringTextInputFormatter.digitsOnly,
                      ),
                      const SizedBox(height: 10),
                      Row(
                        children: [
                          Expanded(
                            flex: 2,
                            child: textControllerWidget(
                              context,
                              provider.addTotalAmountController,
                              "Amount",
                              "Total Amount",
                              (_) {},
                              TextInputType.number,
                              true,
                              FilteringTextInputFormatter.digitsOnly,
                            ),
                          ),
                        ],
                      ),

                      // IconButton(
                      //   icon: const Icon(Icons.delete),
                      //   onPressed: provider.editProductPriceControllers.length > 1
                      //       ? () => provider.editRemoveRow(j)
                      //       : null,
                      // ),
                    ],
                  ),
                ),
              ],
            ),
          ),

          floatingActionButtonLocation:
              FloatingActionButtonLocation.centerFloat,
          floatingActionButton: InkWell(
            onTap: () {
              HapticFeedback.selectionClick();
              if (provider.selectedProducts != null) {
                final productData = {
                  "product_id": provider.selectedProductsId!,
                  "price": provider.addProductPriceController.text,
                  "qty": provider.addQuantityController.text,
                  "net_price": provider.addTotalAmountController.text,
                };
                if (widget.editIndex != null) {
                  provider.updateProduct(widget.editIndex!, productData);
                } else {
                  provider.addProduct(productData);
                }
                print(provider.getJsonEncodedProducts());
                Navigator.pop(context, provider.getJsonEncodedProducts());
              }
            },
            child: Container(
              alignment: Alignment.center,
              height: 45,
              decoration: BoxDecoration(
                color: AppColors.app_blue, //1487C9
                borderRadius: BorderRadius.circular(14.0),
              ),
              margin: EdgeInsets.symmetric(horizontal: 10),
              child: Center(
                child: Text(
                  "Submit",
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
