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:flutter_svg/svg.dart';
import 'package:generp/Notifiers/financeProvider/RequestionListProvider.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:generp/Utils/dropdownTheme.dart';
import 'package:generp/screens/commom/addCommonPayment.dart';
import 'package:get/utils.dart';
import 'package:provider/provider.dart';

import '../../Models/financeModels/addPaymentRequestionResponse.dart';
import '../../Utils/commonServices.dart';

class Submitpaymentrequestionlistsbymode extends StatefulWidget {
  final String mode;
  final String pageTitleName;
  final accountId;

  const Submitpaymentrequestionlistsbymode({
    super.key,
    required this.mode,
    required this.pageTitleName,
    this.accountId,
  });

  @override
  State<Submitpaymentrequestionlistsbymode> createState() =>
      _SubmitpaymentrequestionlistsbymodeState();
}

class _SubmitpaymentrequestionlistsbymodeState
    extends State<Submitpaymentrequestionlistsbymode>
    with RouteAware {
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

  Dropdowntheme ddtheme = Dropdowntheme();
  List<FocusNode> focusNodes = List.generate(11, (index) => FocusNode());
  GlobalKey _globalKey = GlobalKey();
  ScrollController scrollcontroller = ScrollController();

  @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<Requestionlistprovider>(
        context,
        listen: false,
      );
      print("widget.accountId ${widget.accountId}");
      provider.addPaymentRequestionViewAPI(context, widget.mode);
      Future.delayed(Duration(milliseconds: 500), () {
        if (widget.mode == "self" && provider.accounts.length == 1) {
          provider.selectedAccount = provider.accounts.first;
          provider.accountId = provider.accounts.first.id!;
        } else if (widget.mode == "other" && provider.accounts != null) {
          if (widget.accountId != null) {
            provider.selectedAccount = provider.accounts.firstWhereOrNull(
              (element) => element.id == widget.accountId,
            );
            print("sdsd,al;,al${provider.selectedAccount!.id}");
            print("sdsd,al;,al${provider.selectedAccount!.name}");
            provider.accountId =
                provider.accounts
                    .firstWhere((e) => e.id == widget.accountId)!
                    .id!;
            provider.accountValue =
                provider.accounts
                    .firstWhere((e) => e.id == widget.accountId)!
                    .name!;
          }
        }
      });
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // Subscribe to route changes
  }

  @override
  void didPop() {
    // Called when the route is popped (including by swipe gesture)
    if (mounted) {
      var provider = Provider.of<Requestionlistprovider>(
        context,
        listen: false,
      );
      provider.resetForm();
    }
    super.didPop();
  }

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

    super.dispose();
  }

  autofill(res) {
    print("auto");
    var provider = Provider.of<Requestionlistprovider>(context, listen: false);
    if (provider.accounts != null) {
      provider.selectedAccount = provider.accounts.firstWhereOrNull(
        (element) => element.id == res,
      );
      print("sdsd,al;,al${provider.selectedAccount}");
      provider.accountId = provider.accounts.firstWhere((e) => e.id == res).id!;
      provider.accountValue =
          provider.accounts.firstWhere((e) => e.id == res).name!;
    }
  }

  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: () {
                Provider.of<Requestionlistprovider>(
                  context,
                  listen: false,
                ).resetForm();
                return onBackPressed(context);
              },
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  @override
  void deactivate() {
    // TODO: implement deactivate
    super.deactivate();
  }

  Widget _scaffold(BuildContext context) {
    return Consumer<Requestionlistprovider>(
      builder: (context, provider, child) {
        return Scaffold(
          resizeToAvoidBottomInset: true,
          backgroundColor: AppColors.scaffold_bg_color,
          appBar: appbar2New(
            context,
            "${widget.pageTitleName}",
            provider.resetForm,
            SizedBox(width: 0),
            0xFFFFFFFF
          ),
          body: Container(
            padding: EdgeInsets.symmetric(horizontal: 10),
            margin: EdgeInsets.only(top: 10,left: 10,right: 10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
            ),
            child: SingleChildScrollView(
              controller: scrollcontroller,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  TextWidget(context, "Select Account"),
                  DropdownButtonHideUnderline(
                    child: Row(
                      children: [
                        Expanded(
                          flex: 5,
                          child: DropdownButton2<Accounts>(
                            isExpanded: true,
                            hint: Text(
                              'Select Account',
                              style: TextStyle(fontSize: 14),
                              overflow: TextOverflow.ellipsis,
                            ),
                            items:
                                provider.accounts
                                    .map(
                                      (accs) => DropdownMenuItem<Accounts>(
                                        value: accs,
                                        child: Text(
                                          "${accs.name}",
                                          style: const TextStyle(fontSize: 14),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                    )
                                    .toList(),
                            value: provider.selectedAccount,
                            onChanged:
                                (widget.mode == "self" &&
                                        provider.accounts.length == 1)
                                    ? null
                                    : (Accounts? value) {
                                      if (value != null) {
                                        if (provider.accounts.isNotEmpty) {
                                          provider.selectedAccount = value;
                                          print(
                                            "Selected Complaint Type: ${value.name}, ID: ${value.id}",
                                          );
                                          provider.accountId = value.id!;
                                          print(
                                            "hfjkshfg" +
                                                provider.accountId.toString(),
                                          );
                                          provider
                                              .paymentRequestionBankDetailsAPIFunction(
                                                context,
                                                provider.accountId,
                                              );
                                        }
                                      }
                                    },
                            dropdownSearchData: DropdownSearchData(
                              searchInnerWidgetHeight: 50,
                              searchController:
                                  provider.accountSearchController,
                              searchInnerWidget: Padding(
                                padding: const EdgeInsets.all(8),
                                child: TextFormField(
                                  controller: provider.accountSearchController,
                                  decoration: InputDecoration(
                                    isDense: true,
                                    contentPadding: const EdgeInsets.symmetric(
                                      horizontal: 10,
                                      vertical: 8,
                                    ),
                                    hintText: 'Search account...',
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                  ),
                                ),
                              ),
                              searchMatchFn: (item, searchValue) {
                                return item.value?.name?.toLowerCase().contains(
                                      searchValue.toLowerCase(),
                                    ) ??
                                    false;
                              },

                              // Optional: clear search text when dropdown closes
                            ),
                            onMenuStateChange: (isOpen) {
                              if (!isOpen) {
                                provider.accountSearchController.clear();
                              }
                            },
                            buttonStyleData: ddtheme.buttonStyleData,
                            iconStyleData: ddtheme.iconStyleData,
                            menuItemStyleData: ddtheme.menuItemStyleData,
                            dropdownStyleData: ddtheme.dropdownStyleData,
                          ),
                        ),
                        if (widget.mode == "other") ...[
                          SizedBox(width: 5),
                          Expanded(
                            flex: 1,
                            child: InkResponse(
                              onTap: () async {
                                HapticFeedback.selectionClick();
                                var res = await Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder:
                                        (context) => Addcommonpayment(
                                          from: "Requesition",
                                        ),
                                  ),
                                );
                                print("return Response: ${res}");
                                if (res != true) {
                                  provider.addPaymentRequestionViewAPI(
                                    context,
                                    widget.mode,
                                  );
                                  if (res != null) {
                                    print("true");
                                    Future.delayed(Durations.long4, () async {
                                      print("Long411");
                                      autofill(res);
                                    });
                                  }
                                }
                              },
                              child: Container(
                                height: 45,
                                padding: EdgeInsets.all(8),
                                decoration: BoxDecoration(
                                  color: AppColors.app_blue,
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: SvgPicture.asset(
                                  "assets/svg/add_account.svg",
                                  color: Colors.white,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                  errorWidget(context, provider.selectAccountError),

                  if (["self", "admin"].contains(widget.mode)) ...[
                    TextWidget(context, "Select Requisition Type"),
                    DropdownButtonHideUnderline(
                      child: Row(
                        children: [
                          Expanded(
                            child: DropdownButton2<String>(
                              isExpanded: true,
                              hint: Text(
                                'Select Request Type',
                                style: TextStyle(fontSize: 14),
                                overflow: TextOverflow.ellipsis,
                              ),
                              items:
                                  provider.requestingPurposes
                                      .map(
                                        (accs) => DropdownMenuItem<String>(
                                          value: accs,
                                          child: Text(
                                            accs ?? '',
                                            style: const TextStyle(
                                              fontSize: 14,
                                            ),
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                      )
                                      .toList(),
                              value: provider.selectReqPurpose,

                              onChanged: (String? value) {
                                if (value != null) {
                                  provider.selectReqPurpose = value;
                                  print("Selected Complaint Type: ${value},");

                                  print(
                                    "hfjkshfg" +
                                        provider.selectReqPurpose.toString(),
                                  );
                                }
                              },
                              buttonStyleData: ddtheme.buttonStyleData,
                              iconStyleData: ddtheme.iconStyleData,
                              menuItemStyleData: ddtheme.menuItemStyleData,
                              dropdownStyleData: ddtheme.dropdownStyleData,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ] else ...[
                    textControllerWidget(
                      context,
                      provider.reqPurposeController,
                      "Request Purpose",
                      "Enter Request Purpose",
                      provider.updateReqPupose,
                      TextInputType.text,
                      false,
                      null,
                      focusNodes[0],
                      focusNodes[1],
                      TextInputAction.next,
                    ),
                  ],
                  errorWidget(context, provider.reqPurposeError),

                  textControllerWidget(
                    context,
                    provider.descController,
                    "Description",
                    "Enter Description",
                    provider.updateDescription,
                    TextInputType.text,
                    false,
                    null,
                    focusNodes[1],
                    focusNodes[2],
                    TextInputAction.next,
                  ),
                  errorWidget(context, provider.descriptionError),

                  textControllerWidget(
                    context,
                    provider.amountController,
                    "Amount",
                    "Enter Amount",
                    provider.updateAmount,
                    TextInputType.numberWithOptions(),
                    false,
                    null,
                    focusNodes[2],
                    null,
                    TextInputAction.done,
                  ),
                  errorWidget(context, provider.amountError),

                  TextWidget(context, "Select Payment Mode"),
                  DropdownButtonHideUnderline(
                    child: Row(
                      children: [
                        Expanded(
                          child: DropdownButton2<PaymentModes>(
                            isExpanded: true,
                            hint: Text(
                              'Select Payment mode',
                              style: TextStyle(fontSize: 14),
                              overflow: TextOverflow.ellipsis,
                            ),
                            items:
                                provider.paymentModes
                                    .map(
                                      (paymenents) =>
                                          DropdownMenuItem<PaymentModes>(
                                            value: paymenents,
                                            child: Text(
                                              paymenents.name ?? '',
                                              style: const TextStyle(
                                                fontSize: 14,
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                    )
                                    .toList(),
                            value: provider.selectedPayment,
                            onChanged: (PaymentModes? value) {
                              if (value != null) {
                                if (provider.paymentModes.isNotEmpty) {
                                  provider.selectedPayment = value;
                                  print(
                                    "Selected Complaint Type: ${value.name}, ID: ${value.id}",
                                  );
                                  provider.paymentModeId = value.id!;
                                  provider.paymentModeValue = value.name!;
                                  print(
                                    "hfjkshfg" +
                                        provider.paymentModeId.toString(),
                                  );
                                  if ([
                                    "Cheque",
                                    "RTGS",
                                    "IMPS",
                                    "NEFT",
                                    "UPI"
                                  ].contains(provider.paymentModeValue)) {
                                    WidgetsBinding.instance
                                        .addPostFrameCallback((_) {
                                          final context =
                                              _globalKey.currentContext;
                                          if (context != null) {
                                            Scrollable.ensureVisible(
                                              context,
                                              duration: Duration(
                                                milliseconds: 300,
                                              ),
                                              curve: Curves.easeInOut,
                                            );
                                          }
                                        });
                                  }
                                }
                              }
                            },
                            buttonStyleData: ddtheme.buttonStyleData,
                            iconStyleData: ddtheme.iconStyleData,
                            menuItemStyleData: ddtheme.menuItemStyleData,
                            dropdownStyleData: ddtheme.dropdownStyleData,
                          ),
                        ),
                      ],
                    ),
                  ),
                  errorWidget(context, provider.selectPaymentError),

                  if (widget.mode == "other") ...[
                    TextWidget(context, "Select Approval Employee"),
                    DropdownButtonHideUnderline(
                      child: Row(
                        children: [
                          Expanded(
                            child: DropdownButton2<Employees>(
                              isExpanded: true,
                              hint: Text(
                                'Select Approval Employee',
                                style: TextStyle(fontSize: 14),
                                overflow: TextOverflow.ellipsis,
                              ),
                              items:
                                  provider.approvalEmployee
                                      .map(
                                        (paymenents) =>
                                            DropdownMenuItem<Employees>(
                                              value: paymenents,
                                              child: Text(
                                                paymenents.name ?? '',
                                                style: const TextStyle(
                                                  fontSize: 14,
                                                ),
                                                overflow: TextOverflow.ellipsis,
                                              ),
                                            ),
                                      )
                                      .toList(),
                              value: provider.selectedApprovalEmployee,
                              onChanged: (Employees? value) {
                                if (value != null) {
                                  if (provider.approvalEmployee.isNotEmpty) {
                                    provider.selectedApprovalEmployee = value;
                                    print(
                                      "Selected Complaint Type: ${value.name}, ID: ${value.id}",
                                    );
                                    provider.selectedApprovalEmployeeID =
                                        value.id!;
                                    provider.selectedApprovalEmployeeValue =
                                        value.name!;
                                    print(
                                      "hfjkshfg" +
                                          provider.paymentModeId.toString(),
                                    );
                                  }
                                }
                              },
                              buttonStyleData: ddtheme.buttonStyleData,
                              iconStyleData: ddtheme.iconStyleData,
                              menuItemStyleData: ddtheme.menuItemStyleData,
                              dropdownStyleData: ddtheme.dropdownStyleData,
                            ),
                          ),
                        ],
                      ),
                    ),
                    errorWidget(context, provider.selectPaymentError),
                  ],

                  InkResponse(
                    onTap: () {
                      HapticFeedback.selectionClick();
                      _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(
                          "File Attachment",
                          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: [
                          Expanded(
                            flex: 4,
                            child: Text(
                              "${provider.imagePath}",
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                color: AppColors.semi_black,
                                fontSize: 11,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                          Expanded(
                            flex: 1,
                            child: InkResponse(
                              onTap: () {
                                provider.imagePicked = 0;
                                provider.imagePath = null;
                                provider.imageFilePath = null;
                              },
                              child: SvgPicture.asset(
                                "assets/svg/ic_close.svg",
                                width: 15,
                                height: 15,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                  errorWidget(context, provider.FileError),
                  SizedBox(height: 3, key: _globalKey),
                  if ([
                    "Cheque",
                    "RTGS",
                    "IMPS",
                    "NEFT",
                  ].contains(provider.paymentModeValue)) ...[


                    textControllerWidget(
                      context,
                      provider.bankNameController,
                      "Bank Name",
                      "Enter Bank Name",
                      provider.updateBankName,
                      TextInputType.text,
                      false,
                      null,
                      focusNodes[3],
                      focusNodes[4],
                      TextInputAction.next,
                    ),
                    errorWidget(context, provider.bankNameError),

                    textControllerWidget(
                      context,
                      provider.bankBranchController,
                      "Bank Branch",
                      "Enter Bank Branch",
                      provider.updateBankBranch,
                      TextInputType.text,
                      false,
                      null,
                      focusNodes[4],
                      focusNodes[5],
                      TextInputAction.next,
                    ),
                    errorWidget(context, provider.bankBranchError),

                    textControllerWidget(
                      context,
                      provider.bankAccNumberController,
                      "Account Number",
                      "Enter Account Number",
                      provider.updateNumber,
                      TextInputType.number,
                      false,
                      FilteringTextInputFormatter.digitsOnly,
                      focusNodes[5],
                      focusNodes[6],
                      TextInputAction.next,
                    ),
                    errorWidget(context, provider.bankNumberError),

                    textControllerWidget(
                      context,
                      provider.bankIfscController,
                      "Bank IFSC",
                      "Enter Bank IFSC",
                      provider.updateIFSC,
                      TextInputType.text,
                      false,
                      null,
                      focusNodes[6],
                      focusNodes[7],
                      TextInputAction.next,
                    ),
                    errorWidget(context, provider.bankIFSCError),
                  ],
                  if ([
                    "Cheque",
                    "RTGS",
                    "IMPS",
                    "NEFT",
                    "UPI",
                  ].contains(provider.paymentModeValue)) ...[
                    textControllerWidget(
                      context,
                      provider.bankAcHolderController,
                      "Bank Account Holder Name",
                      "Enter Bank Account Holder Name",
                      provider.updateHolder,
                      TextInputType.text,
                      false,
                      null,
                      focusNodes[7],
                      null,
                      TextInputAction.done,
                    ),
                    errorWidget(context, provider.bankHolderError),
                  ],
                  if (provider.paymentModeValue == "UPI") ...[
                    textControllerWidget(
                      context,
                      provider.bankUpiController,
                      "UPI ID",
                      "Enter UPI ID",
                      provider.updateUPI,
                      TextInputType.text,
                      false,
                      null,
                      focusNodes[8],
                      null,
                      TextInputAction.done,
                    ),
                    errorWidget(context, provider.UPIError),

                    SizedBox(height: 20,)
                  ],
                ],
              ),
            ),
          ),
          floatingActionButtonLocation:
              FloatingActionButtonLocation.centerFloat,
          bottomNavigationBar: InkResponse(
            onTap:
                provider.submitClicked
                    ? null
                    : () {
                  HapticFeedback.selectionClick();
                      provider.submitClicked = true;

                      provider.addPaymentRequestionSubmitAPI(
                        context,
                        widget.mode,
                        provider.selectedApprovalEmployeeID,
                      );
                    },
            child: Container(
              height: 45,
              alignment: Alignment.center,
              margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
              decoration: BoxDecoration(
                color: AppColors.app_blue,
                borderRadius: BorderRadius.circular(15),
              ),
              child:
                  provider.submitClicked
                      ? CircularProgressIndicator.adaptive(
                        valueColor: AlwaysStoppedAnimation(AppColors.white),
                      )
                      : Text(
                        "Submit",
                        style: TextStyle(
                          fontSize: 15,
                          fontFamily: "JakartaMedium",
                          color: Colors.white,
                        ),
                      ),
            ),
          ),
        );
      },
    );
  }

  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<Requestionlistprovider>(
                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: Container(
                                height: 35,
                                child: Text("Select photo from gallery"),
                              ),
                            ),
                            SizedBox(height: 10),
                            InkWell(
                              onTap: () {
                                Navigator.of(context).pop(false);
                                provider.imgFromCamera(context);
                              },
                              child: Container(
                                height: 35,
                                child: Text("Capture photo from camera"),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
