import 'dart:async';
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:get/get.dart';
import 'package:provider/provider.dart';
import 'package:generp/screens/notifierExports.dart';
import 'package:tuple/tuple.dart';
import '../../Models/ordersModels/AddOrderPaymentSelectAccountResponse.dart';
import '../../Models/ordersModels/AddOrderPaymentSelectOrderResponse.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';
import '../../Utils/dropdownTheme.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:generp/Utils/commonServices.dart';

class AddpaymentScreen extends StatefulWidget {
  final pageTitleName;
  final mode;

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

  @override
  State<AddpaymentScreen> createState() => _AddpaymentScreenState();
}

class _AddpaymentScreenState extends State<AddpaymentScreen> {
  Timer? _debounce;
  FocusNode focusNode = FocusNode();
  List<FocusNode> focusNodes = List.generate(5, (index) => FocusNode());
  Dropdowntheme ddtheme = Dropdowntheme();

  String? selectedValue;
  final TextEditingController textEditingController = TextEditingController();
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var provider = Provider.of<Addpaymentprovider>(context, listen: false);
      if (provider.dateNow == null) {
        provider.setDate(DateTime.now());
      }
      provider.ordersAddPaymentAPIViewFunction(context);
      provider.ordersAddPaymentSelectAccountAPIFunction(
        context,
        widget.mode,
        provider.selectedAccountID,
        '',
      );
    });
  }

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

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

  @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"
        ? Consumer<Addpaymentprovider>(
          builder: (context, provider, child) {
            return WillPopScope(
              child: SafeArea(
                top: false,
                bottom: Platform.isIOS ? false : true,
                child: Scaffold(
                  resizeToAvoidBottomInset: true,
                  backgroundColor: AppColors.white,
                  appBar: appbar2New(
                    context,
                    "${widget.pageTitleName}",
                    provider.resetForm,
                    SizedBox(width: 0),
                    0xFFFFFFFF,
                  ),
                  body: Container(
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          TextWidget(context, "Account"),
                          Container(
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: AppColors.text_field_color,
                              borderRadius: BorderRadius.circular(14),
                            ),
                            child: ListTile(
                              title: TextFormField(
                                focusNode: focusNode,
                                onTapUpOutside: (event) {
                                  focusNode.unfocus();
                                },
                                controller: provider.dropDownSearchController,
                                onChanged: (value) async {
                                  Future.delayed(
                                    Duration(milliseconds: 100),
                                    () async {
                                      await provider
                                          .ordersAddPaymentSelectAccountAPIFunction(
                                            context,
                                            widget.mode,
                                            provider.selectedAccountID,
                                            value,
                                          );
                                    },
                                  );
                                },
                                decoration: InputDecoration(
                                  enabledBorder: InputBorder.none,
                                  focusedBorder: InputBorder.none,
                                  isDense: true,
                                  contentPadding: const EdgeInsets.symmetric(
                                    horizontal: 0,
                                    vertical: 8,
                                  ),
                                  hintText: 'Select Account Type',
                                  hintStyle: const TextStyle(fontSize: 14),
                                  border: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                ),
                              ),

                              trailing: InkResponse(
                                onTap: () {
                                  if (focusNode.hasFocus) {
                                    focusNode.unfocus();
                                  } else {
                                    FocusScope.of(
                                      context,
                                    ).requestFocus(focusNode);
                                  }
                                },
                                child: SvgPicture.asset(
                                  "assets/svg/arrow_dropdown.svg",
                                  height: 25,
                                  width: 20,
                                ),
                              ),
                            ),
                          ),

                          if (provider.accountList.isNotEmpty &&
                              focusNode.hasFocus) ...[
                            Card(
                              margin: EdgeInsets.symmetric(horizontal: 0),
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 10),
                                height: widget.mode == "self" ? 50 : 150,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(16),
                                ),
                                child: Scrollbar(
                                  thickness: 2.5,
                                  radius: Radius.circular(6),
                                  thumbVisibility: true,
                                  child: ListView.builder(
                                    itemCount: provider.accountList.length,
                                    shrinkWrap: true,
                                    physics: AlwaysScrollableScrollPhysics(),
                                    itemBuilder: (context, index) {
                                      return InkResponse(
                                        onTap: () async {
                                          if (provider.accountList.isNotEmpty) {
                                            provider.selectedAccountList =
                                                provider.accountList[index];

                                            print(
                                              "Selected Complaint Type: ${provider.accountList[index].text}, ID: ${provider.accountList[index].id}",
                                            );
                                            provider.selectedAccountID =
                                                provider.accountList[index].id!;
                                            provider.selectedAccountName =
                                                provider
                                                    .accountList[index]
                                                    .text!;
                                            print(
                                              "hfjkshfg${provider.selectedAccountID}",
                                            );
                                            provider
                                                .dropDownSearchController
                                                .text = provider
                                                    .accountList[index]
                                                    .text!;
                                          }
                                          provider
                                              .ordersAddPaymentSelectOrderAPIFunction(
                                                context,
                                                provider.selectedAccountID,
                                              );
                                          provider.accountList = [];
                                        },
                                        child: SizedBox(
                                          height: 45,
                                          child: Align(
                                            alignment: Alignment.centerLeft,
                                            child: Text(
                                              provider.accountList[index].text!,
                                            ),
                                          ),
                                        ),
                                      );
                                    },
                                  ),
                                ),
                              ),
                            ),
                          ],

                          ///enwewe
                          errorWidget(context, provider.selectAccountError),

                          textControllerWidget(
                            context,
                            provider.amountController,
                            "Amount",
                            "Enter Amount",
                            provider.onChangeAmount,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                            focusNodes[0],
                            null,
                            TextInputAction.next,
                          ),
                          errorWidget(context, provider.amountError),

                          ///Addorderbutton
                          if (provider.selectedAccountID != null) ...[
                            InkResponse(
                              onTap: () {
                                // if (provider.selectedOrderIds.length < provider.orderList.length) {
                                provider.addNewRow();
                                // } 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 (provider.orderAmountControllers.isNotEmpty) ...[
                              Row(
                                children: [
                                  Expanded(
                                    child: ListView.builder(
                                      itemCount:
                                          provider
                                              .orderAmountControllers
                                              .length,
                                      physics: NeverScrollableScrollPhysics(),
                                      shrinkWrap: true,
                                      itemBuilder: (context, index) {
                                        return Row(
                                          children: [
                                            Expanded(
                                              flex: 3,
                                              child: SizedBox(
                                                child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: [
                                                    TextWidget(
                                                      context,
                                                      "Order",
                                                    ),
                                                    Row(
                                                      children: [
                                                        Expanded(
                                                          child: DropdownButtonHideUnderline(
                                                            child: DropdownButton2<
                                                              OrderList
                                                            >(
                                                              isExpanded: true,
                                                              hint: Text(
                                                                'Select Account Type',
                                                                style:
                                                                    TextStyle(
                                                                      fontSize:
                                                                          14,
                                                                    ),
                                                                overflow:
                                                                    TextOverflow
                                                                        .ellipsis,
                                                              ),
                                                              items:
                                                                  provider
                                                                      .orderList
                                                                      .map(
                                                                        (
                                                                          ord,
                                                                        ) => DropdownMenuItem<
                                                                          OrderList
                                                                        >(
                                                                          value:
                                                                              ord,
                                                                          child: Text(
                                                                            "(Order Number: ${ord.orderNumber}) + (Order Amount: ${ord.totalAmount}) + (Balance Amount: ${ord.balanceAmount}) + (Date Time: ${ord.createdDatetime})" ??
                                                                                '',
                                                                            style: const TextStyle(
                                                                              fontSize:
                                                                                  14,
                                                                            ),
                                                                            overflow:
                                                                                TextOverflow.ellipsis,
                                                                          ),
                                                                        ),
                                                                      )
                                                                      .toList(),
                                                              // value: provider.selectedOrderLists,
                                                              value:
                                                                  provider.selectedOrderIds[index] !=
                                                                          null
                                                                      ? provider.orderList.firstWhere(
                                                                        (
                                                                          product,
                                                                        ) =>
                                                                            product.orderId ==
                                                                            provider.selectedOrderIds[index],
                                                                      )
                                                                      : null,
                                                              onChanged: (
                                                                OrderList?
                                                                value,
                                                              ) {
                                                                if (value !=
                                                                    null) {
                                                                  if (provider
                                                                      .orderList
                                                                      .isNotEmpty) {
                                                                    provider.selectedOrderLists =
                                                                        value;
                                                                    print(
                                                                      "Selected Complaint Type: ${value.orderId}, ID: ${value.orderNumber}",
                                                                    );
                                                                    provider.updateSelectedOrderId(
                                                                      index,
                                                                      provider
                                                                          .selectedOrderLists,
                                                                    );
                                                                    // provider.selectedOrderIds = value!.orderId!;
                                                                    // provider.selectedOrderNumbers = value!.orderNumber!;
                                                                    print(
                                                                      "hfjkshfg${provider.selectedOrderIds}",
                                                                    );
                                                                  }
                                                                }
                                                              },
                                                              buttonStyleData:
                                                                  ddtheme
                                                                      .buttonStyleData,
                                                              iconStyleData:
                                                                  ddtheme
                                                                      .iconStyleData,
                                                              menuItemStyleData:
                                                                  ddtheme
                                                                      .menuItemStyleData,
                                                              dropdownStyleData:
                                                                  ddtheme
                                                                      .dropdownStyleData,
                                                            ),
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            ),

                                            SizedBox(width: 10),
                                            Expanded(
                                              flex: 2,
                                              child: textControllerWidget(
                                                context,
                                                provider
                                                    .orderAmountControllers[index],
                                                "Order Amount",
                                                "Enter Order Amount",
                                                (p0) {
                                                  provider
                                                      .updateAdjustedAmount();
                                                },
                                                TextInputType.number,
                                                false,
                                                FilteringTextInputFormatter
                                                    .digitsOnly,
                                                null,
                                                null,
                                                TextInputAction.next,
                                              ),
                                            ),
                                            // SizedBox(width: 10),
                                            //
                                            // IconButton(
                                            //   icon: Icon(Icons.delete),
                                            //   onPressed: provider.orderAmountControllers.length > 1
                                            //       ? () => provider.removeRow(index)
                                            //       : null, // Prevent removing the last row
                                            // ),
                                          ],
                                        );
                                      },
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ],

                          textControllerWidget(
                            context,
                            provider.orderAdjustedAmountController,
                            "Order Adjusted Amount",
                            "Enter Order Adjusted Amount",
                            provider.onChangeorderAdjustedAmount,
                            TextInputType.number,
                            false,
                            FilteringTextInputFormatter.digitsOnly,
                            focusNodes[1],
                            null,
                            TextInputAction.done,
                          ),
                          errorWidget(
                            context,
                            provider.orderAdjustedAmountError,
                          ),
                          TextWidget(context, "Description"),
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<String>(
                                    isExpanded: true,
                                    hint: const Row(
                                      children: [
                                        Expanded(
                                          child: Text(
                                            'Select Advance Payment',
                                            style: TextStyle(fontSize: 14),
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                      ],
                                    ),
                                    items:
                                        provider.description
                                            .map(
                                              (pm) => DropdownMenuItem<String>(
                                                value: pm,
                                                child: Text(
                                                  pm,
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                ),
                                              ),
                                            )
                                            .toList(),
                                    value: provider.selectedDescription,
                                    onChanged: (value) {
                                      if (value != null) {
                                        provider.selectedDescription = value;
                                        print(
                                          "statusId:${provider.selectedDescription}",
                                        );
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(context, provider.descriptionError),

                          TextWidget(context, "Payment Received Date"),
                          GestureDetector(
                            onTap: () {
                              provider.showDatePickerDialog(context);
                            },
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Expanded(
                                  child: Container(
                                    height: 50,
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                      color: AppColors.text_field_color,
                                      borderRadius: BorderRadius.circular(14),
                                    ),
                                    child: Padding(
                                      padding: const EdgeInsets.fromLTRB(
                                        10.0,
                                        0.0,
                                        10,
                                        0,
                                      ),
                                      child: TextFormField(
                                        controller:
                                            provider
                                                .paymentReceivedDateController,
                                        keyboardType: TextInputType.text,
                                        enabled: false,
                                        maxLines: 1,
                                        readOnly: true,
                                        onChanged: (value) {},
                                        decoration: InputDecoration(
                                          hintText: "Enter Date",
                                          hintStyle: TextStyle(
                                            fontWeight: FontWeight.w400,
                                            color: Color(0xFFB4BEC0),
                                            fontSize: 14,
                                          ),

                                          enabledBorder: InputBorder.none,
                                          disabledBorder: InputBorder.none,
                                          focusedBorder: InputBorder.none,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(context, provider.dateError),

                          TextWidget(context, "Select Payment Mode"),
                          DropdownButtonHideUnderline(
                            child: Row(
                              children: [
                                Expanded(
                                  child: DropdownButton2<String>(
                                    isExpanded: true,
                                    hint: const Row(
                                      children: [
                                        Expanded(
                                          child: Text(
                                            'Select Payment Mode',
                                            style: TextStyle(fontSize: 14),
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                      ],
                                    ),
                                    items:
                                        provider.paymentMode
                                            .map(
                                              (pm) => DropdownMenuItem<String>(
                                                value: pm,
                                                child: Text(
                                                  pm,
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                ),
                                              ),
                                            )
                                            .toList(),
                                    value: provider.selectedPaymentMode,
                                    onChanged: (value) {
                                      if (value != null) {
                                        provider.selectedPaymentMode = value;
                                        print(
                                          "statusId:${provider.selectedPaymentMode}",
                                        );
                                      }
                                    },
                                    buttonStyleData: ddtheme.buttonStyleData,
                                    iconStyleData: ddtheme.iconStyleData,
                                    menuItemStyleData:
                                        ddtheme.menuItemStyleData,
                                    dropdownStyleData:
                                        ddtheme.dropdownStyleData,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          errorWidget(context, provider.paymentModeError),

                          textControllerWidget(
                            context,
                            provider.paymentRefController,
                            "Payment Reference No",
                            "Enter Payment Reference No. / Cheque No. / UTR No.",
                            provider.onChangepaymentRef,
                            TextInputType.text,
                            false,
                            null,
                            focusNodes[2],
                            null,
                            TextInputAction.done,
                          ),
                          errorWidget(context, provider.paymentRefError),

                          InkResponse(
                            onTap: () {
                              _showAttachmentSheet(context);
                            },
                            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(
                                  "Payment Reference",
                                  style: TextStyle(
                                    fontFamily: "JakartaMedium",
                                    color: AppColors.app_blue,
                                  ),
                                ),
                              ),
                            ),
                          ),
                          if (provider.imagePicked == 1 &&
                              provider.imagePath != null) ...[
                            Padding(
                              padding: const EdgeInsets.symmetric(
                                vertical: 4.0,
                              ),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    "${provider.imagePath}",
                                    style: TextStyle(
                                      color: AppColors.semi_black,
                                      fontSize: 11,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  InkResponse(
                                    onTap: () {
                                      provider.imagePicked = 0;
                                      provider.imagePath = null;
                                      provider.imageFilePath = null;
                                    },
                                    child: SvgPicture.asset(
                                      "assets/svg/ic_close.svg",
                                      width: 15,
                                      height: 15,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ],
                      ),
                    ),
                  ),
                  floatingActionButtonLocation:
                      FloatingActionButtonLocation.centerFloat,
                  bottomNavigationBar: InkResponse(
                    onTap:
                        provider.submitClicked
                            ? null
                            : () {
                              provider.submitClicked = true;
                              provider.selectedOrders = provider.getFormData();
                              provider.ordersAddPaymentAPISubmitFunction(
                                context,
                                provider.selectedAccountID,
                                provider.selectedDescription,
                                provider.selectedOrders,
                                provider.selectedPaymentMode,
                              );
                            },
                    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:
                          provider.submitClicked
                              ? CircularProgressIndicator.adaptive(
                                valueColor: AlwaysStoppedAnimation(
                                  Colors.white,
                                ),
                              )
                              : Text(
                                "Submit",
                                style: TextStyle(
                                  fontSize: 15,
                                  fontFamily: "JakartaMedium",
                                  color: Colors.white,
                                ),
                              ),
                    ),
                  ),
                ),
              ),
              onWillPop: () async {
                provider.resetForm();
                return _onBackPressed(context);
              },
            );
          },
        )
        : NoNetwork(context);
  }

  Future<void> _showAttachmentSheet(BuildContext context) {
    return showModalBottomSheet(
      useSafeArea: true,
      isDismissible: true,
      isScrollControlled: true,
      showDragHandle: true,
      backgroundColor: Colors.white,
      enableDrag: true,
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return SafeArea(
              child: Consumer<Addpaymentprovider>(
                builder: (context, provider, child) {
                  return Padding(
                    padding: EdgeInsets.only(
                      bottom:
                          MediaQuery.of(
                            context,
                          ).viewInsets.bottom, // This handles keyboard
                    ),
                    child: Container(
                      margin: EdgeInsets.only(
                        bottom: 15,
                        left: 15,
                        right: 15,
                        top: 10,
                      ),

                      child: SingleChildScrollView(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Align(
                              alignment: Alignment.center,
                              child: Text(
                                "Select Source",
                                style: TextStyle(
                                  color: AppColors.app_blue,
                                  fontFamily: "JakrtaMedium",
                                  fontSize: 16,
                                ),
                              ),
                            ),
                            SizedBox(height: 15),
                            InkWell(
                              onTap: () {
                                Navigator.of(context).pop(false);
                                provider.imgFromGallery(context);
                              },
                              child: SizedBox(
                                height: 35,
                                child: Text("Select photo from gallery"),
                              ),
                            ),
                            SizedBox(height: 10),
                            InkWell(
                              onTap: () {
                                Navigator.of(context).pop(false);
                                provider.imgFromCamera(context);
                              },
                              child: SizedBox(
                                height: 35,
                                child: Text("Capture photo from camera"),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
