import 'dart:io';

import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:generp/Utils/dropdownTheme.dart';
import 'package:generp/screens/crm/generateQuotationAddEditProduct.dart';
import 'package:provider/provider.dart';

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

class Generatequotationscreenold extends StatefulWidget {
  final leadId;

  const Generatequotationscreenold({super.key, required this.leadId});

  @override
  State<Generatequotationscreenold> createState() =>
      _GeneratequotationscreenoldState();
}

class _GeneratequotationscreenoldState extends State<Generatequotationscreenold> {
  Dropdowntheme ddtheme = Dropdowntheme();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      final provider = Provider.of<Crmgeneratequotationprovider>(
        context,
        listen: false,
      );
      await provider.crmLeadDetailsGenerateQuoteViewAPIFunction(
        context,
        widget.leadId,
      );

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

  @override
  Widget build(BuildContext context) {
    return Consumer<Crmgeneratequotationprovider>(
      builder: (context, provider, child) {
        return WillPopScope(
          onWillPop: () async {
            // provider.resetForm();
            return true;
          },
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS ? false : true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,
              backgroundColor: AppColors.scaffold_bg_color,
              appBar: appbar2(
                context,
                "Generate Quotation",
                provider.resetForm,
                const SizedBox(width: 0),
              ),
              body: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 10,
                      ),
                      margin: EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 10,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Column(
                        children: [
                          textControllerWidget(
                            context,
                            provider.mailIdController,
                            "Email Id",
                            "Enter Email Id",
                            provider.onChangemailId,
                            TextInputType.emailAddress,
                            false,
                            null,
                          ),
                          errorWidget(context, provider.mailIdError),

                          textControllerWidget(
                            context,
                            provider.mobileController,
                            "Mobile Number",
                            "Enter Mobile Number",
                            provider.onChangemobile,
                            TextInputType.phone,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                          ),
                          errorWidget(context, provider.mobileError),

                          textControllerWidget(
                            context,
                            provider.subjectsController,
                            "Subject",
                            "Enter Subject",
                            provider.onChangesubjects,
                            TextInputType.text,
                            false,
                            null,
                          ),
                          errorWidget(context, provider.subjectsError),
                        ],
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 10,
                      ),
                      margin: EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 10,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Column(
                        children: [
                          InkResponse(
                            onTap: () async {
                              var res = await Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder:
                                        (context) =>
                                        Generatequotationaddeditproduct(leadId: widget.leadId,),
                                    settings: RouteSettings(name: 'Generatequotationaddeditproduct')
                                ),

                              );

                            },
                            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 (provider.leadProductsList.isNotEmpty ||
                              provider
                                  .editProductPriceControllers
                                  .isNotEmpty) ...[
                            ListView.builder(
                              itemCount:
                              provider.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<
                                                  LeadProducts
                                              >(
                                                isExpanded: true,
                                                hint: const Text(
                                                  'Select Product',
                                                  style: TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                  overflow:
                                                  TextOverflow.ellipsis,
                                                ),
                                                items:
                                                provider.leadProductsList
                                                    .map(
                                                      (
                                                      ord,
                                                      ) => DropdownMenuItem<
                                                      LeadProducts
                                                  >(
                                                    value: ord,
                                                    child: Text(
                                                      "${ord.productName}",
                                                      style:
                                                      const TextStyle(
                                                        fontSize:
                                                        14,
                                                      ),
                                                      overflow:
                                                      TextOverflow
                                                          .ellipsis,
                                                    ),
                                                  ),
                                                )
                                                    .toList(),
                                                value:
                                                provider.selectedProductIds[j] !=
                                                    null
                                                    ? provider
                                                    .leadProductsList
                                                    .firstWhere(
                                                      (ord) =>
                                                  ord.id ==
                                                      provider
                                                          .selectedProductIds[j],
                                                  orElse:
                                                      () =>
                                                  provider
                                                      .leadProductsList[0],
                                                )
                                                    : null,
                                                onChanged: (
                                                    LeadProducts? value,
                                                    ) {
                                                  if (value != null) {
                                                    provider
                                                        .updateSelectedProductIds(
                                                      j,
                                                      value,
                                                    );
                                                    provider.selectedProductIds[j] =
                                                        value.id?.toString() ??
                                                            '';
                                                    provider.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,
                                              provider
                                                  .editProductPriceControllers[j],
                                              "Product Price",
                                              "Enter Product Price",
                                                  (value) =>
                                                  provider.updateTotalAmount(j),
                                              TextInputType.number,
                                              false,
                                              FilteringTextInputFormatter
                                                  .digitsOnly,
                                            ),
                                          ),
                                        ],
                                      ),
                                      const SizedBox(height: 10),
                                      Row(
                                        children: [
                                          Expanded(
                                            flex: 2,
                                            child: textControllerWidget(
                                              context,
                                              provider
                                                  .editQuantityControllers[j],
                                              "Quantity",
                                              "Enter Quantity",
                                                  (value) =>
                                                  provider.updateTotalAmount(j),
                                              TextInputType.number,
                                              false,
                                              FilteringTextInputFormatter
                                                  .digitsOnly,
                                            ),
                                          ),
                                        ],
                                      ),
                                      const SizedBox(height: 10),
                                      Row(
                                        children: [
                                          Expanded(
                                            flex: 2,
                                            child: textControllerWidget(
                                              context,
                                              provider
                                                  .editTotalAmountControllers[j],
                                              "Amount",
                                              "Total Amount",
                                                  (_) {},
                                              TextInputType.number,
                                              true,
                                              FilteringTextInputFormatter
                                                  .digitsOnly,
                                            ),
                                          ),
                                        ],
                                      ),
                                      // IconButton(
                                      //   icon: const Icon(Icons.delete),
                                      //   onPressed: provider.editProductPriceControllers.length > 1
                                      //       ? () => provider.editRemoveRow(j)
                                      //       : null,
                                      // ),
                                    ],
                                  ),
                                );
                              },
                            ),
                          ],
                        ],
                      ),
                    ),

                    Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 10,
                      ),
                      margin: EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 10,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Column(
                        children: [
                          textControllerWidget(
                            context,
                            provider.taxesController,
                            "Taxes",
                            "Enter Taxes",
                            provider.onChangetaxes,
                            TextInputType.text,
                            false,
                            null,
                          ),
                          errorWidget(context, provider.taxesError),

                          textControllerWidget(
                            context,
                            provider.SpecialNoteController,
                            "Special Note",
                            "Enter Special Note",
                            provider.onChangeSpecialNote,
                            TextInputType.text,
                            false,
                            null,
                          ),
                          errorWidget(context, provider.SpecialNoteError),

                          textControllerWidget(
                            context,
                            provider.forController,
                            "FOR",
                            "Enter FOR",
                            provider.onChangefor,
                            TextInputType.text,
                            false,
                            null,
                          ),
                          errorWidget(context, provider.forError),

                          textControllerWidget(
                            context,
                            provider.paymentTermsController,
                            "Payment Terms",
                            "Enter Payment Terms",
                            provider.onChangepaymentTerms,
                            TextInputType.text,
                            false,
                            null,
                          ),
                          errorWidget(context, provider.paymentTermsError),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

              floatingActionButtonLocation:
              FloatingActionButtonLocation.centerFloat,
              bottomNavigationBar: Material(
                elevation: 10,
                shadowColor: Colors.black54,
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black26,
                        blurRadius: 10,
                        offset: Offset(0, -2),
                      ),
                    ],
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Expanded(
                        child: InkResponse(
                          onTap:
                          provider.submitLoading
                              ? null
                              : () {
                            //genquotedown
                            final insertedData = provider.getFormData();
                            provider
                                .crmLeadDetailsGenerateQuoteSubmitAPIFunction(
                              context,
                              widget.leadId,
                              insertedData,
                              "genquotedown",
                            );
                          },
                          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(10),
                            ),
                            child:
                            provider.submitLoading
                                ? CircularProgressIndicator.adaptive(
                              valueColor: AlwaysStoppedAnimation<Color>(
                                AppColors.app_blue,
                              ),
                            )
                                : SvgPicture.asset(
                              "assets/svg/download_quote.svg",
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: 10),
                      Expanded(
                        child: InkResponse(
                          onTap:
                          provider.submitLoading
                              ? null
                              : () {
                            //genquotemail,
                            final insertedData = provider.getFormData();
                            provider
                                .crmLeadDetailsGenerateQuoteSubmitAPIFunction(
                              context,
                              widget.leadId,
                              insertedData,
                              "genquotemail",
                            );
                          },
                          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(10),
                            ),
                            child:
                            provider.submitLoading
                                ? CircularProgressIndicator.adaptive(
                              valueColor: AlwaysStoppedAnimation<Color>(
                                AppColors.app_blue,
                              ),
                            )
                                : SvgPicture.asset(
                              "assets/svg/mail_quote.svg",
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: 10),
                      Expanded(
                        child: InkResponse(
                          onTap:
                          provider.submitLoading
                              ? null
                              : () {
                            //genquotewhatsapp,
                            final insertedData = provider.getFormData();
                            provider
                                .crmLeadDetailsGenerateQuoteSubmitAPIFunction(
                              context,
                              widget.leadId,
                              insertedData,
                              "genquotewhatsapp",
                            );
                          },
                          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(10),
                            ),
                            child:
                            provider.submitLoading
                                ? CircularProgressIndicator.adaptive(
                              valueColor: AlwaysStoppedAnimation<Color>(
                                AppColors.app_blue,
                              ),
                            )
                                : SvgPicture.asset(
                              "assets/svg/whatsapp_quote.svg",
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: 10),
                      Expanded(
                        child: InkResponse(
                          onTap:
                          provider.submitLoading
                              ? null
                              : () {
                            //genquotewhatsappbymynum,
                            final insertedData = provider.getFormData();
                            provider
                                .crmLeadDetailsGenerateQuoteSubmitAPIFunction(
                              context,
                              widget.leadId,
                              insertedData,
                              "genquotewhatsappbymynum",
                            );
                          },
                          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(10),
                            ),
                            child:
                            provider.submitLoading
                                ? CircularProgressIndicator.adaptive(
                              valueColor: AlwaysStoppedAnimation<Color>(
                                AppColors.app_blue,
                              ),
                            )
                                : SvgPicture.asset(
                              "assets/svg/whatsapp_quote_self.svg",
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
