import 'dart:async';
import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

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

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

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

  @override
  State<Editpaymentdetailsbymode> createState() =>
      _EditpaymentdetailsbymodeState();
}

class _EditpaymentdetailsbymodeState extends State<Editpaymentdetailsbymode> {
  Timer? _debounce;
  FocusNode focusNode = FocusNode();

  String? selectedValue;
  final TextEditingController textEditingController = TextEditingController();
  List<FocusNode> focusNodes = List.generate(5, (index) => FocusNode());
  Dropdowntheme ddtheme = Dropdowntheme();
  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,
        '',
      );
      // "description":provider.paymentDetails!.description,
      // "amount":provider.paymentDetails!.amount,
      // "payment_mode":provider.paymentDetails!.paymentType,
      // "pay_ref":provider.paymentDetails!.refNo,
      // "pay_received_date":provider.paymentDetails!.paymentDate,
      provider.selectedDescription = widget.values['description'];
      provider.amountController.text = widget.values['amount'];
      provider.selectedPaymentMode = widget.values['payment_mode'];
      provider.paymentRefController.text = widget.values['pay_ref'];
      provider.paymentReceivedDateController.text =
          widget.values['pay_received_date'];
    });
  }

  @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")
        ? Platform.isAndroid
            ? WillPopScope(
              onWillPop: () async {
                Provider.of<Addpaymentprovider>(
                  context,
                  listen: false,
                ).resetForm();
                Provider.of<Editpaymentprovider>(
                  context,
                  listen: false,
                ).resetForm();

                return onBackPressed(context);
              },
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(BuildContext context) {
    return Consumer2<Addpaymentprovider, Editpaymentprovider>(
      builder: (context, provider, editProvider, 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.shrink(),
                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, "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),
                      textControllerWidget(
                        context,
                        provider.amountController,
                        "Amount",
                        "Enter Amount",
                        provider.onChangeAmount,
                        TextInputType.number,
                        false,
                        FilteringTextInputFormatter.digitsOnly,
                        focusNodes[0],
                        null,
                        TextInputAction.done,
                      ),
                      errorWidget(context, provider.amountError),

                      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[1],
                        null,
                        TextInputAction.done,
                      ),
                      errorWidget(context, provider.paymentRefError),
                      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),
                    ],
                  ),
                ),
              ),
              floatingActionButtonLocation:
                  FloatingActionButtonLocation.centerFloat,
              floatingActionButton: InkResponse(
                onTap:
                    editProvider.submitLoading
                        ? null
                        : () {
                          editProvider.submitLoading = true;
                          editProvider.editPaymentDetailsAPIFunction(
                            context,
                            widget.values["payment_id"],
                            provider.selectedDescription,
                            provider.selectedPaymentMode,
                            provider.paymentRefController.text,
                            provider.formattedDateToSend,
                            provider.amountController.text,
                          );
                        },
                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<Color>(
                              AppColors.white,
                            ),
                          )
                          : Text(
                            "Submit",
                            style: TextStyle(
                              fontSize: 15,
                              fontFamily: "JakartaMedium",
                              color: Colors.white,
                            ),
                          ),
                ),
              ),
            ),
          ),
          onWillPop: () async {
            provider.resetForm();
            return _onBackPressed(context);
          },
        );
      },
    );
  }
}
