import 'dart:io';

import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Models/ordersModels/EditPaymentDetailsAdjustedOrdersViewResponse.dart';
import 'package:provider/provider.dart';

import '../../Models/ordersModels/AddOrderPaymentSelectOrderResponse.dart';
import '../../Notifiers/ordersProvider/addPaymentProvider.dart';
import '../../Notifiers/ordersProvider/editPaymentProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';
import '../../Utils/dropdownTheme.dart';

class Editadjustedorderlist extends StatefulWidget {
  final mode;
  final pageTitleName;
  final values;

  const Editadjustedorderlist({
    super.key,
    this.mode,
    this.pageTitleName,
    this.values,
  });

  @override
  State<Editadjustedorderlist> createState() => _EditadjustedorderlistState();
}

class _EditadjustedorderlistState extends State<Editadjustedorderlist> {
  Dropdowntheme ddtheme = Dropdowntheme();
  List<FocusNode> focusNodes = List.generate(3, (index) => FocusNode());

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      final editProvider = Provider.of<Editpaymentprovider>(
        context,
        listen: false,
      );
      editProvider.checkDropdownselected();

      await editProvider.editPaymentDetailsAdjustedOrdersViewAPIFunction(
        context,
        widget.values["payment_id"],
      );

      if (widget.values != null && widget.values['orders'] != null) {
        final ordersFromWidget = widget.values['orders'];

        for (int i = 0; i < ordersFromWidget.length; i++) {
          final widgetOrderNumber = ordersFromWidget[i]['order_number'];
          final widgetAmount = ordersFromWidget[i]['amount'];
          final matchedOrder = editProvider.paidList.firstWhere(
            (order) => order.orderNumber == widgetOrderNumber,
            orElse: () {
              return editProvider.paidList[0];
            },
          );

          editProvider.editAddNewRow(); // Adds controller + dropdown slot
          editProvider.editOrderAmountControllers[i].text = widgetAmount;
          editProvider.updateSelectedPaidOrderId(i, matchedOrder);
        }
      }
    });
  }

  @override
  void dispose() {
    focusNodes.map((e) => e.dispose());
    super.dispose();
  }

  Future<bool> _onBackPressed(BuildContext context) async {
    Navigator.pop(context, true);
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<Editpaymentprovider>(
      builder: (context, editProvider, child) {
        return WillPopScope(
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS ? false : true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,
              backgroundColor: AppColors.scaffold_bg_color,
              appBar: appbar2(
                context,
                "${widget.pageTitleName}",
                editProvider.resetForm,
                SizedBox(width: 0),
              ),
              body: Container(
                padding: EdgeInsets.symmetric(horizontal: 10),
                // decoration: BoxDecoration(
                //   color: Colors.white,
                //   borderRadius: BorderRadius.circular(20),
                // ),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if (editProvider.editOrderList.isNotEmpty) ...[
                        InkResponse(
                          onTap: () {
                            // if (provider.selectedOrderIds.length < provider.orderList.length) {
                            editProvider.editAddNewRow2();
                            // } else {
                            //   ScaffoldMessenger.of(context).showSnackBar(
                            //     SnackBar(
                            //       content: Text('No more unique order IDs or statuses available'),
                            //     ),
                            //   );
                            // }
                          },
                          child: Container(
                            margin: EdgeInsets.symmetric(vertical: 10),
                            height: 45,
                            width: MediaQuery.of(context).size.width,
                            decoration: BoxDecoration(
                              color: Color(0xFFE6F6FF),
                              borderRadius: BorderRadius.circular(12),
                              border: Border.all(
                                color: AppColors.app_blue,
                                width: 0.5,
                              ),
                            ),
                            child: Center(
                              child: Text(
                                "+ Add Order",
                                style: TextStyle(
                                  fontFamily: "JakartaMedium",
                                  color: AppColors.app_blue,
                                ),
                              ),
                            ),
                          ),
                        ),
                        if (editProvider.paidList.isNotEmpty) ...[
                          Row(
                            children: [
                              Expanded(
                                child: ListView.builder(
                                  itemCount: editProvider.paidList.length,
                                  physics: NeverScrollableScrollPhysics(),
                                  shrinkWrap: true,
                                  itemBuilder: (context, index) {
                                    return Container(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 10,
                                      ),
                                      margin: EdgeInsets.symmetric(
                                        vertical: 10,
                                      ),
                                      decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.circular(20),
                                      ),
                                      child: Column(
                                        children: [
                                          Row(
                                            children: [
                                              Expanded(
                                                flex: 3,
                                                child: SizedBox(
                                                  child: Column(
                                                    crossAxisAlignment:
                                                        CrossAxisAlignment
                                                            .start,
                                                    children: [
                                                      TextWidget(
                                                        context,
                                                        "Order",
                                                      ),
                                                      Row(
                                                        children: [
                                                          Expanded(
                                                            child: DropdownButtonHideUnderline(
                                                              child: DropdownButton2<
                                                                EditPaidList
                                                              >(
                                                                isExpanded:
                                                                    true,
                                                                hint: Text(
                                                                  'Select Account Type',
                                                                  style:
                                                                      TextStyle(
                                                                        fontSize:
                                                                            14,
                                                                      ),
                                                                  overflow:
                                                                      TextOverflow
                                                                          .ellipsis,
                                                                ),
                                                                items:
                                                                    editProvider
                                                                        .paidList
                                                                        .map(
                                                                          (
                                                                            ord,
                                                                          ) => DropdownMenuItem<
                                                                            EditPaidList
                                                                          >(
                                                                            value:
                                                                                ord,
                                                                            child: Text(
                                                                              "(Order Number: ${ord.orderNumber}) + (Order Amount: ${ord.orderAmount}) + (Balance Amount: ${ord.balanceAmount})" ??
                                                                                  '',
                                                                              style: const TextStyle(
                                                                                fontSize:
                                                                                    14,
                                                                              ),
                                                                              overflow:
                                                                                  TextOverflow.ellipsis,
                                                                            ),
                                                                          ),
                                                                        )
                                                                        .toList(),
                                                                // value:
                                                                //     editProvider
                                                                //         .selectedPaidList,
                                                                value: editProvider
                                                                    .paidList
                                                                    .firstWhere(
                                                                      (
                                                                        product,
                                                                      ) =>
                                                                          product
                                                                              .orderId ==
                                                                          editProvider
                                                                              .selectedPaidOrderIDs[index],
                                                                    ),
                                                                // value:editProvider.paidList.firstWhere(
                                                                //       (
                                                                //       ord,
                                                                //       ) =>
                                                                //   ord.orderId ==
                                                                //       editProvider.selectedPaidOrderIDs[index],
                                                                //   orElse:
                                                                //       () =>
                                                                //   editProvider.paidList[0],
                                                                // ),
                                                                onChanged: (
                                                                  EditPaidList?
                                                                  value,
                                                                ) {
                                                                  if (value !=
                                                                      null) {
                                                                    if (editProvider
                                                                        .paidList
                                                                        .isNotEmpty) {
                                                                      editProvider
                                                                              .editselectedPaidList =
                                                                          value;
                                                                      print(
                                                                        "Selected Complaint Type: ${value.orderId}, ID: ${value.orderNumber}",
                                                                      );
                                                                      editProvider.updateSelectedPaidOrderId(
                                                                        index,
                                                                        editProvider
                                                                            .editselectedPaidList,
                                                                      );
                                                                      // provider.selectedOrderIds = value!.orderId!;
                                                                      // provider.selectedOrderNumbers = value!.orderNumber!;
                                                                      // print(
                                                                      //   "hfjkshfg" +
                                                                      //       provider.selectedOrderIds.toString(),
                                                                    }
                                                                  }
                                                                },
                                                                buttonStyleData:
                                                                    ddtheme
                                                                        .buttonStyleData,
                                                                iconStyleData:
                                                                    ddtheme
                                                                        .iconStyleData,
                                                                menuItemStyleData:
                                                                    ddtheme
                                                                        .menuItemStyleData,
                                                                dropdownStyleData:
                                                                    ddtheme
                                                                        .dropdownStyleData,
                                                              ),
                                                            ),
                                                          ),
                                                        ],
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),

                                          SizedBox(width: 10),
                                          Row(
                                            children: [
                                              Expanded(
                                                flex: 2,
                                                child: textControllerWidget(
                                                  context,
                                                  editProvider
                                                      .editOrderAmountControllers[index],
                                                  "Order Amount",
                                                  "Enter Order Amount",
                                                  (p0) {},
                                                  TextInputType.number,
                                                  false,
                                                  FilteringTextInputFormatter
                                                      .digitsOnly,
                                                  focusNodes[0],
                                                  focusNodes[1],
                                                  TextInputAction.next,
                                                ),
                                              ),
                                            ],
                                          ),
                                          SizedBox(height: 10),
                                          // SizedBox(width: 10),
                                          //
                                          // IconButton(
                                          //   icon: Icon(Icons.delete),
                                          //   onPressed: provider.orderAmountControllers.length > 1
                                          //       ? () => provider.removeRow(index)
                                          //       : null, // Prevent removing the last row
                                          // ),
                                        ],
                                      ),
                                    );
                                  },
                                ),
                              ),
                            ],
                          ),
                        ],
                        if (editProvider.editOrderList.isNotEmpty) ...[
                          if (editProvider
                              .editOrderAmountControllers2
                              .isNotEmpty)
                            Row(
                              children: [
                                Expanded(
                                  child: ListView.builder(
                                    itemCount:
                                        editProvider.editOrderList.length,
                                    physics: NeverScrollableScrollPhysics(),
                                    shrinkWrap: true,
                                    itemBuilder: (context, j) {
                                      return Container(
                                        padding: EdgeInsets.symmetric(
                                          horizontal: 10,
                                        ),
                                        margin: EdgeInsets.symmetric(
                                          vertical: 10,
                                        ),
                                        decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius: BorderRadius.circular(
                                            20,
                                          ),
                                        ),
                                        child: Column(
                                          children: [
                                            Row(
                                              children: [
                                                Expanded(
                                                  flex: 3,
                                                  child: SizedBox(
                                                    child: Column(
                                                      crossAxisAlignment:
                                                          CrossAxisAlignment
                                                              .start,
                                                      children: [
                                                        TextWidget(
                                                          context,
                                                          "Order",
                                                        ),
                                                        Row(
                                                          children: [
                                                            Expanded(
                                                              child: DropdownButtonHideUnderline(
                                                                child: DropdownButton2<
                                                                  EditOrderList
                                                                >(
                                                                  isExpanded:
                                                                      true,
                                                                  hint: Text(
                                                                    'Select Account Type',
                                                                    style: TextStyle(
                                                                      fontSize:
                                                                          14,
                                                                    ),
                                                                    overflow:
                                                                        TextOverflow
                                                                            .ellipsis,
                                                                  ),
                                                                  items:
                                                                      editProvider
                                                                          .editOrderList
                                                                          .map(
                                                                            (
                                                                              ord,
                                                                            ) => DropdownMenuItem<
                                                                              EditOrderList
                                                                            >(
                                                                              value:
                                                                                  ord,
                                                                              child: Text(
                                                                                "(Order Number: ${ord.orderNumber}) + (Order Amount: ${ord.totalAmount}) + (Balance Amount: ${ord.balanceAmount})" ??
                                                                                    '',
                                                                                style: const TextStyle(
                                                                                  fontSize:
                                                                                      14,
                                                                                ),
                                                                                overflow:
                                                                                    TextOverflow.ellipsis,
                                                                              ),
                                                                            ),
                                                                          )
                                                                          .toList(),
                                                                  value:
                                                                      editProvider.selectedOrderIDs[j] !=
                                                                                  null &&
                                                                              editProvider.editOrderList.isNotEmpty
                                                                          ? editProvider.editOrderList.firstWhere(
                                                                            (
                                                                              ord,
                                                                            ) =>
                                                                                ord.orderId ==
                                                                                editProvider.selectedOrderIDs[j],
                                                                            orElse:
                                                                                () =>
                                                                                    editProvider.editOrderList[0],
                                                                          )
                                                                          : null,
                                                                  onChanged: (
                                                                    EditOrderList?
                                                                    value,
                                                                  ) {
                                                                    if (value !=
                                                                        null) {
                                                                      if (editProvider
                                                                          .editOrderList
                                                                          .isNotEmpty) {
                                                                        editProvider.selectedOrderList =
                                                                            value;
                                                                        print(
                                                                          "Selected Complaint Type: ${value.orderId}, ID: ${value.orderNumber}",
                                                                        );
                                                                        editProvider.updateSelectedOrderId(
                                                                          j,
                                                                          editProvider
                                                                              .selectedOrderList,
                                                                        );
                                                                        // provider.selectedOrderIds = value!.orderId!;
                                                                        // provider.selectedOrderNumbers = value!.orderNumber!;
                                                                        // print(
                                                                        //   "hfjkshfg" +
                                                                        //       provider.selectedOrderIds.toString(),
                                                                      }
                                                                    }
                                                                  },
                                                                  buttonStyleData:
                                                                      ddtheme
                                                                          .buttonStyleData,
                                                                  iconStyleData:
                                                                      ddtheme
                                                                          .iconStyleData,
                                                                  menuItemStyleData:
                                                                      ddtheme
                                                                          .menuItemStyleData,
                                                                  dropdownStyleData:
                                                                      ddtheme
                                                                          .dropdownStyleData,
                                                                ),
                                                              ),
                                                            ),
                                                          ],
                                                        ),
                                                      ],
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            ),

                                            SizedBox(width: 10),
                                            Row(
                                              children: [
                                                Expanded(
                                                  flex: 2,
                                                  child: textControllerWidget(
                                                    context,
                                                    editProvider
                                                        .editOrderAmountControllers2[j],
                                                    "Order Amount",
                                                    "Enter Order Amount",
                                                    (p0) {},
                                                    TextInputType.number,
                                                    false,
                                                    FilteringTextInputFormatter
                                                        .digitsOnly,
                                                    null,
                                                    null,
                                                    TextInputAction.done,
                                                  ),
                                                ),
                                              ],
                                            ),
                                            SizedBox(height: 10),
                                            // SizedBox(width: 10),
                                            //
                                            // IconButton(
                                            //   icon: Icon(Icons.delete),
                                            //   onPressed: provider.orderAmountControllers.length > 1
                                            //       ? () => provider.removeRow(index)
                                            //       : null, // Prevent removing the last row
                                            // ),
                                          ],
                                        ),
                                      );
                                    },
                                  ),
                                ),
                              ],
                            ),
                        ],
                      ],
                    ],
                  ),
                ),
              ),
              floatingActionButtonLocation:
                  FloatingActionButtonLocation.centerFloat,
              bottomNavigationBar: InkResponse(
                onTap:
                    editProvider.submitLoading
                        ? null
                        : () {
                          editProvider.submitLoading = true;
                          final updatedData = editProvider.getFormDataUpdate();
                          print(updatedData);
                          final insertedData = editProvider.getFormData();
                          print(insertedData);
                          editProvider
                              .editPaymentDetailsAdjustedOrdersUpdateAPIFunction(
                                context,
                                widget.values["payment_id"],
                                updatedData,
                                insertedData,
                              );
                        },
                child: Container(
                  height: 45,
                  alignment: Alignment.center,
                  margin: EdgeInsets.symmetric(horizontal: 10, vertical: 15),
                  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                  decoration: BoxDecoration(
                    color: AppColors.app_blue,
                    borderRadius: BorderRadius.circular(15),
                  ),
                  child:
                      editProvider.submitLoading
                          ? CircularProgressIndicator.adaptive(
                            valueColor: AlwaysStoppedAnimation(
                              AppColors.app_blue,
                            ),
                          )
                          : Text(
                            "Submit",
                            style: TextStyle(
                              fontSize: 15,
                              fontFamily: "JakartaMedium",
                              color: Colors.white,
                            ),
                          ),
                ),
              ),
            ),
          ),
          onWillPop: () async {
            editProvider.resetForm();
            return _onBackPressed(context);
          },
        );
      },
    );
  }
}
