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/custom_snackbar.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() {
    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();
        provider.remarkController.clear(); // Clear remarks too
      } else {
        provider.prefillProductForEdit(widget.editIndex!);
      }
    });
  }

  @override
  void 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(),
                                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.selectedProductsRemark = value.remarks;
                                    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,
                            ),
                          ),
                        ],
                      ),
                      TextWidget(context, "Remarks"),
                      Container(
                        margin: EdgeInsets.only(bottom: 6),
                        decoration: BoxDecoration(
                          color: AppColors.text_field_color,
                          borderRadius: BorderRadius.circular(14),
                        ),
                        child: TextFormField(
                          controller: provider.remarkController,
                          maxLines: 3,
                          enabled: true,
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 14,
                          ),
                          decoration: InputDecoration(
                            hintText: "Enter remark",
                            hintStyle: TextStyle(
                              color: Colors.grey.shade500,
                              fontSize: 14,
                            ),
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.symmetric(
                                horizontal: 12, vertical: 12),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
          floatingActionButtonLocation:
          FloatingActionButtonLocation.centerFloat,
          floatingActionButton: InkWell(
            onTap: () {
              HapticFeedback.selectionClick();

              // Validate required fields
              if (provider.selectedProducts == null) {
                //
                CustomSnackBar.showWarning(
                  context: context,
                  message: "Please select a product",
                );
                return;
              }

              if (provider.addProductPriceController.text.isEmpty) {
                CustomSnackBar.showWarning(
                  context: context,
                  message: "Please enter product price",
                );
                return;
              }

              if (provider.addQuantityController.text.isEmpty) {
                CustomSnackBar.showWarning(
                  context: context,
                  message: "Please enter quantity",
                );

                return;
              }

              // Prepare product data - FIX: Use .text for remarks
              final productData = {
                "product_id": provider.selectedProductsId!,
                "price": provider.addProductPriceController.text,
                "qty": provider.addQuantityController.text,
                "net_price": provider.addTotalAmountController.text,
                "remarks": provider.remarkController.text, // FIXED: Use .text
              };

              if (widget.editIndex != null) {
                provider.updateProduct(widget.editIndex!, productData);
                print("Product updated at index ${widget.editIndex}");
              } else {
                provider.addProduct(productData);
                print("New product added");
              }

              print("Product data: ${provider.getJsonEncodedProducts()}");

              // Show success message
              CustomSnackBar.showSuccess(
                context: context,
                message: widget.editIndex != null
                    ? "Product updated successfully!"
                    : "Product added successfully!",
              );

              // Close screen after a short delay to show the success message
              Future.delayed(Duration(milliseconds: 1500), () {
                if (mounted) {
                  Navigator.pop(context, true); // Return true to indicate success
                }
              });
            },
            child: Container(
              alignment: Alignment.center,
              height: 45,
              decoration: BoxDecoration(
                color: AppColors.app_blue,
                borderRadius: BorderRadius.circular(14.0),
              ),
              margin: EdgeInsets.symmetric(horizontal: 10),
              child: Center(
                child: Text(
                  widget.editIndex != null ? "Update Product" : "Add Product",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget TextWidget(context, text) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 5.0, top: 8.0),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w500,
          color: AppColors.semi_black,
        ),
      ),
    );
  }
}