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:provider/provider.dart';

import '../../Models/crmModels/crmLeadDetailsGenerateQuotationViewResponse.dart';
import '../../Notifiers/crmProvider/crmGenerateQuotationProvider.dart';
import '../../Notifiers/crmProvider/crmLeadDetailsProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonServices.dart';
import '../../Utils/commonWidgets.dart';
import '../../Utils/dropdownTheme.dart';

class Generatequotationaddeditproduct extends StatefulWidget {
  final leadId;
  final type;
  final product;
  final index;

  const Generatequotationaddeditproduct({
    super.key,
    required this.leadId,
    this.type,
    this.product,
    this.index,
  });

  @override
  State<Generatequotationaddeditproduct> createState() =>
      _GeneratequotationaddeditproductState();
}

class _GeneratequotationaddeditproductState
    extends State<Generatequotationaddeditproduct> {
  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<Crmgeneratequotationprovider>(
        context,
        listen: false,
      );
      provider.crmLeadDetailsGenerateQuoteViewAPIFunction(
        context,
        widget.leadId,
      );
      // provider.resetForm();
      if (widget.type == "add") {
        // Initialize controllers and dropdowns after API call
        provider.addEditInitializeForm(context);
      } else if (widget.type == "edit") {
        print(widget.index);
        print(widget.product);

        provider.preFillFormForEdit(widget.product, widget.index);
      }
    });
  }

  @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<Crmgeneratequotationprovider>(
      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.selectedAddEditProductId,
                                        )
                                        : null,
                                onChanged: (Products? value) {
                                  if (value != null) {
                                    provider.selectedProducts = value;
                                    provider.selectedAddEditProductId =
                                        value.id!;
                                    provider.selectedAddEditProductName =
                                        value.name;
                                    print(value.id.toString());
                                    provider
                                        .crmSelectedProductDetailsApiFunction(
                                          context,
                                          value.id.toString(),
                                        );
                                  }
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),

                      const SizedBox(height: 10),
                      textControllerWidget(
                        context,
                        provider.addEditProductPriceController,
                        "Product Price",
                        "Enter Product Price",
                        provider.addEditUpdateTotalAmount,
                        TextInputType.number,
                        false,
                        FilteringTextInputFormatter.digitsOnly,
                      ),
                      const SizedBox(height: 10),
                      textControllerWidget(
                        context,
                        provider.addEditQuantityController,
                        "Quantity",
                        "Enter Quantity",
                        provider.addEditUpdateTotalAmount,
                        TextInputType.number,
                        false,
                        FilteringTextInputFormatter.digitsOnly,
                      ),
                      const SizedBox(height: 10),
                      Row(
                        children: [
                          Expanded(
                            flex: 2,
                            child: textControllerWidget(
                              context,
                              provider.addEditTotalAmountController,
                              "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: () {
              if (provider.selectedProducts != null) {
                LeadProducts newProduct;
                if (widget.type == "add") {
                  newProduct = LeadProducts(
                    productId: provider.selectedAddEditProductId,
                    productName: provider.selectedAddEditProductName,
                    price: provider.addEditProductPriceController.text,

                    qty: provider.addEditQuantityController.text,
                    prodTotalPrice: provider.addEditTotalAmountController.text,
                  );
                  provider.leadProductsList.add(newProduct);
                  provider.productRows.add({
                    "product_id": provider.selectedAddEditProductId!,
                    "price": provider.addEditProductPriceController.text,
                    "qty": provider.addEditQuantityController.text,
                    "net_price": provider.addEditTotalAmountController.text,
                  });
                  Navigator.pop(context, newProduct);
                } else if (widget.type == "edit") {
                  final updatedProduct = LeadProducts(
                    productId: provider.selectedAddEditProductId,
                    productName: provider.selectedAddEditProductName,
                    price: provider.addEditProductPriceController.text,
                    qty: provider.addEditQuantityController.text,
                    prodTotalPrice: provider.addEditTotalAmountController.text,
                  );
                  provider.editProduct(widget.index!, updatedProduct);
                  Navigator.pop(context, updatedProduct);
                }

                // if (widget.index != null) {
                //   // Editing existing product
                //   provider.editProduct(widget.index!, newProduct);
                // } else {
                //   // Adding new product
                //   provider.addProduct(newProduct);
                // }
              }
            },
            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),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
