import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:generp/Models/ordersModels/AddOrderViewResponse.dart';
import 'package:provider/provider.dart';

import '../../Notifiers/ordersProvider/addOrderProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonServices.dart';
import '../../Utils/commonWidgets.dart';
import '../../Utils/dropdownTheme.dart';

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

  @override
  State<Addorderaddproduct> createState() => _AddorderaddproductState();
}

class _AddorderaddproductState extends State<Addorderaddproduct> {
  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<Addorderprovider>(
        context,
        listen: false,
      );
      if(widget.type == "Add"){
        provider.selectedSaleProducts = null;
        provider.selectedSingleSaleProductID = null;
        provider.selectedSaleProductName = null;
        provider.ProductController.clear();
        provider.PriceController.clear();
        provider.QuantityController.clear();
        provider.CGSTController.clear();
        provider.SGSTController.clear();
        provider.IGSTController.clear();
        provider.TotalPriceController.clear();
        provider.TaxableValueController.clear();
        provider.QuantityController.text = "1";
        provider.CGSTController.text = "9";
        provider.SGSTController.text = "9";
        provider.IGSTController.text = "0";
      }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<Addorderprovider>(
      builder: (context, provider, child) {
        return Scaffold(
          resizeToAvoidBottomInset: true,

          appBar: appbarNew(context, "Generate Quotation", 0xFFFFFFFF),
          backgroundColor: AppColors.scaffold_bg_color,
          body:SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [

                // Product Rows (Horizontal ListView)
                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: [
                      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.selectedSingleSaleProductID !=
                                          null
                                          ? provider.saleProducts.firstWhere(
                                            (product) =>
                                        product.id ==
                                            provider
                                                .selectedSingleSaleProductID,
                                      )
                                          : null,

                                      onChanged: (SaleProducts? value) {
                                        if (value != null) {
                                          if (provider
                                              .saleProducts
                                              .isNotEmpty) {
                                            provider.selectedSaleProducts =
                                                value;
                                            provider.PriceController.text = value.price!;
                                            provider.notifyListeners();
                                            provider.updateProductCalculations();
                                            // provider.updateSelectedSingleProduct(
                                            //
                                            //   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.PriceController,
                                    "Price",
                                    "Enter Price",
                                        (p0) {},
                                    TextInputType.number,
                                    false,
                                    null,
                                    null,
                                    null,
                                    TextInputAction.next,
                                  ),
                                ),
                                const SizedBox(width: 8.0),

                                Expanded(
                                  child: textControllerWidget(
                                    context,
                                    provider.QuantityController,
                                    "Quantity",
                                    "Enter Quantity",
                                        (p0) {
                                      provider.updateProductCalculations();
                                    },
                                    TextInputType.number,
                                    false,
                                    null,
                                    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.CGSTController,
                                    "CGST %",
                                    "Enter CGST %",
                                        (p0) {
                                          provider.updateProductCalculations();
                                    },
                                    TextInputType.number,
                                    false,
                                    null,
                                    null,
                                    null,
                                    TextInputAction.next,
                                  ),
                                ),
                                const SizedBox(width: 8.0),
                                Expanded(
                                  child: textControllerWidget(
                                    context,
                                    provider.SGSTController,
                                    "SGST %",
                                    "Enter SGST %",
                                        (p0) {
                                          provider.updateProductCalculations();
                                    },
                                    TextInputType.number,
                                    false,
                                    null,
                                    null,
                                    null,
                                    TextInputAction.next,
                                  ),
                                ),
                                const SizedBox(width: 8.0),

                                Expanded(
                                  child: textControllerWidget(
                                    context,
                                    provider.IGSTController,
                                    "IGST %",
                                    "Enter IGST %",
                                        (p0) {
                                          provider.updateProductCalculations();
                                    },
                                    TextInputType.number,
                                    false,
                                    null,
                                    null,
                                    null,
                                    TextInputAction.next,
                                  ),
                                ),
                              ],
                            ),
                            const SizedBox(height: 8.0),
                            Row(
                              children: [

                                Expanded(
                                  child: textControllerWidget(
                                    context,
                                    provider.TaxableValueController,
                                    "Total Price",
                                    "Enter Total Price",
                                        (p0) {
                                          provider.updateProductCalculations();
                                    },
                                    TextInputType.number,
                                    true,
                                    null,
                                    null,
                                    null,
                                    TextInputAction.next,
                                  ),
                                ),

                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),

                const SizedBox(height: 20),


                // Submit Button
              ],
            ),
          ),

          floatingActionButtonLocation:
          FloatingActionButtonLocation.centerFloat,
          floatingActionButton: InkWell(
            onTap: () {

              if (provider.selectedSaleProducts != null) {

                final productData = {
                  'product_id': provider.selectedSingleSaleProductID,
                  'qty': provider.QuantityController.text,
                  'price': provider.PriceController.text,
                  'cgst_p': provider.CGSTController.text,
                  'sgst_p': provider.SGSTController.text,
                  'igst_p': provider.IGSTController.text,
                  'total_price': provider.TaxableValueController.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),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
