import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/cupertino.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Models/financeModels/addReceiptPaymentResponse.dart';
import 'package:generp/Utils/dropdownTheme.dart';
import 'package:provider/provider.dart';
import '../../Notifiers/financeProvider/paymentReceiptsProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonServices.dart';
import '../../Utils/commonWidgets.dart';

class Addpaymentreceiptlist extends StatefulWidget {
  final pageTitleName;
  const Addpaymentreceiptlist({super.key, this.pageTitleName});

  @override
  State<Addpaymentreceiptlist> createState() => _AddpaymentreceiptlistState();
}

class _AddpaymentreceiptlistState extends State<Addpaymentreceiptlist> {
  Dropdowntheme ddtheme = Dropdowntheme();
  List<FocusNode> focusNodes = List.generate(12, (index) => FocusNode());

  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<Paymentreceiptsprovider>(
        context,
        listen: false,
      );
      provider.addReceiptPaymentRequestionViewAPI(context);
      provider.submitClicked = false;
    });
  }

  @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: () => onBackPressed(context),
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(BuildContext context) {
    return Consumer<Paymentreceiptsprovider>(
      builder: (context, provider, child) {
        return Scaffold(
          resizeToAvoidBottomInset: true,
          backgroundColor: AppColors.scaffold_bg_color,
          appBar: appbar2New(
            context,
            "${widget.pageTitleName}",
            provider.resetForm,
            SizedBox.shrink(),
            0xFFFFFFFF,
          ),
          body: Scrollbar(
            thumbVisibility: false,
            child: SingleChildScrollView(
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 10),
                decoration: BoxDecoration(
                  color: AppColors.white,
                  borderRadius: BorderRadius.circular(20),
                ),
                margin: EdgeInsets.only(top: 10, left: 10, right: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    TextWidget(context, "Account"),
                    DropdownButtonHideUnderline(
                      child: Row(
                        children: [
                          Expanded(
                            child: DropdownButton2<Accounts>(
                              isExpanded: true,
                              hint: Text(
                                'Select Account',
                                style: TextStyle(fontSize: 14),
                                overflow: TextOverflow.ellipsis,
                              ),
                              items: [
                                ...provider.receiptAccounts.map(
                                  (accs) => DropdownMenuItem<Accounts>(
                                    value: accs,
                                    child: Text(
                                      accs.name ?? '',
                                      style: const TextStyle(fontSize: 14),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                ),
                              ],
                              value: provider.selectreceiptAccounts,
                              onChanged: (Accounts? value) {
                                if (value != null) {
                                  if (provider.receiptAccounts.isNotEmpty) {
                                    provider.selectreceiptAccounts = value;
                                    print(
                                      "Selected Complaint Type: ${value.name}, ID: ${value.id}",
                                    );
                                    provider.receiptAccountId = value.id!;
                                    provider.receiptAccountValue = value.name!;
                                    print(
                                      "hfjkshfg${provider.receiptAccountId}",
                                    );
                                  }
                                }
                              },
                              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,
                            ),
                          ),
                        ],
                      ),
                    ),
                    errorWidget(context, provider.selectAccountError),
                    TextWidget(context, "Payment Account"),
                    DropdownButtonHideUnderline(
                      child: Row(
                        children: [
                          Expanded(
                            child: DropdownButton2<ReceiptAccounts>(
                              isExpanded: true,
                              hint: Text(
                                'Select Account',
                                style: TextStyle(fontSize: 14),
                                overflow: TextOverflow.ellipsis,
                              ),
                              items:
                                  provider.receiptPaymentAccounts
                                      .map(
                                        (accs) =>
                                            DropdownMenuItem<ReceiptAccounts>(
                                              value: accs,
                                              child: Text(
                                                accs.name ?? '',
                                                style: const TextStyle(
                                                  fontSize: 14,
                                                ),
                                                overflow: TextOverflow.ellipsis,
                                              ),
                                            ),
                                      )
                                      .toList(),
                              value: provider.selectreceiptPaymentAccounts,
                              onChanged: (ReceiptAccounts? value) {
                                if (value != null) {
                                  if (provider
                                      .receiptPaymentAccounts
                                      .isNotEmpty) {
                                    provider.selectreceiptPaymentAccounts =
                                        value;
                                    print(
                                      "Selected Complaint Type: ${value.name}, ID: ${value.id}",
                                    );
                                    provider.receiptPaymentAccountsID =
                                        value.id!;
                                    provider.receiptPaymentAccountsValue =
                                        value.name!;
                                    print(
                                      "hfjkshfg${provider.receiptPaymentAccountsID}",
                                    );
                                  }
                                }
                              },
                              dropdownSearchData: DropdownSearchData(
                                searchInnerWidgetHeight: 50,
                                searchController:
                                    provider.paymentAccountSearchController,
                                searchInnerWidget: Padding(
                                  padding: const EdgeInsets.all(8),
                                  child: TextFormField(
                                    controller:
                                        provider.paymentAccountSearchController,
                                    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.paymentAccountSearchController
                                      .clear();
                                }
                              },
                              buttonStyleData: ddtheme.buttonStyleData,
                              iconStyleData: ddtheme.iconStyleData,
                              menuItemStyleData: ddtheme.menuItemStyleData,
                              dropdownStyleData: ddtheme.dropdownStyleData,
                            ),
                          ),
                        ],
                      ),
                    ),
                    errorWidget(context, provider.selectPaymentAccountError),

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

                    ///payment date toBE
                    TextWidget(context, "Receipt 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.dateController,
                                  keyboardType: TextInputType.text,
                                  enabled: false,
                                  maxLines: 1,
                                  readOnly: true,
                                  onChanged: (value) {},
                                  focusNode: focusNodes[1],
                                  onTapUpOutside: (event) {
                                    if (focusNodes[1].hasFocus) {
                                      focusNodes[1].unfocus();
                                    }
                                  },
                                  textInputAction: TextInputAction.done,
                                  onEditingComplete: () {
                                    focusNodes[1].unfocus();
                                  },
                                  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<PaymentModes>(
                              isExpanded: true,
                              hint: Text(
                                'Select Payment mode',
                                style: TextStyle(fontSize: 14),
                                overflow: TextOverflow.ellipsis,
                              ),
                              items:
                                  provider.receiptPaymentModes
                                      .map(
                                        (paymenents) =>
                                            DropdownMenuItem<PaymentModes>(
                                              value: paymenents,
                                              child: Text(
                                                paymenents.name ?? '',
                                                style: const TextStyle(
                                                  fontSize: 14,
                                                ),
                                                overflow: TextOverflow.ellipsis,
                                              ),
                                            ),
                                      )
                                      .toList(),
                              value: provider.selectreceiptPaymentModes,
                              onChanged: (PaymentModes? value) {
                                if (value != null) {
                                  if (provider.receiptPaymentModes.isNotEmpty) {
                                    provider.selectreceiptPaymentModes = value;
                                    print(
                                      "Selected Complaint Type: ${value.name}, ID: ${value.id}",
                                    );
                                    provider.receiptPaymentModesID = value.id!;
                                    provider.receiptPaymentModesValues =
                                        value.name!;
                                    print(
                                      "hfjkshfg${provider.receiptPaymentModesID}",
                                    );
                                  }
                                }
                              },
                              buttonStyleData: ddtheme.buttonStyleData,
                              iconStyleData: ddtheme.iconStyleData,
                              menuItemStyleData: ddtheme.menuItemStyleData,
                              dropdownStyleData: ddtheme.dropdownStyleData,
                            ),
                          ),
                        ],
                      ),
                    ),
                    errorWidget(context, provider.paymentModeError),
                    if ([
                      "Cheque",
                      "RTGS",
                      "IMPS",
                      "NEFT",
                    ].contains(provider.paymentModeValue)) ...[
                      textControllerWidget(
                        context,
                        provider.bankNameController,
                        "Bank Name",
                        "Enter Bank Name",
                        provider.updateBankName,
                        TextInputType.text,
                        false,
                        null,
                        focusNodes[2],
                        focusNodes[3],
                        TextInputAction.next,
                      ),
                      errorWidget(context, provider.bankNameError),
                      textControllerWidget(
                        context,
                        provider.bankBranchController,
                        "Bank Branch",
                        "Enter Bank Branch",
                        provider.updateBankBranch,
                        TextInputType.text,
                        false,
                        null,
                        focusNodes[3],
                        focusNodes[4],
                        TextInputAction.next,
                      ),
                      errorWidget(context, provider.bankBranchError),
                      textControllerWidget(
                        context,
                        provider.bankAccNumberController,
                        "Account Number",
                        "Enter Account Number",
                        provider.updateNumber,
                        TextInputType.number,
                        false,
                        FilteringTextInputFormatter.digitsOnly,
                        focusNodes[4],
                        focusNodes[5],
                        TextInputAction.next,
                      ),
                      errorWidget(context, provider.bankNumberError),
                      textControllerWidget(
                        context,
                        provider.bankIfscController,
                        "Bank IFSC",
                        "Enter Bank IFSC",
                        provider.updateIFSC,
                        TextInputType.text,
                        false,
                        null,
                        focusNodes[5],
                        focusNodes[6],
                        TextInputAction.next,
                      ),
                      errorWidget(context, provider.bankIFSCError),
                      textControllerWidget(
                        context,
                        provider.bankAcHolderController,
                        "Bank Account Holder Name",
                        "Enter Bank Account Holder Name",
                        provider.updateHolder,
                        TextInputType.text,
                        false,
                        null,
                        focusNodes[6],
                        focusNodes[8],
                        TextInputAction.next,
                      ),
                      errorWidget(context, provider.bankHolderError),
                    ] else if (provider.paymentModeValue == "UPI") ...[
                      textControllerWidget(
                        context,
                        provider.bankUpiController,
                        "UPI ID",
                        "Enter UPI ID",
                        provider.updateUPI,
                        TextInputType.text,
                        false,
                        null,
                        focusNodes[7],
                        focusNodes[8],
                        TextInputAction.next,
                      ),
                      errorWidget(context, provider.UPIError),
                    ],
                    textControllerWidget(
                      context,
                      provider.paymentReferenceController,
                      "Payment Reference Number",
                      "Enter Payment Reference Number",
                      provider.updatereference,
                      TextInputType.text,
                      false,
                      null,
                      focusNodes[8],
                      focusNodes[9],
                      TextInputAction.next,
                    ),
                    errorWidget(context, provider.paymentreferenceError),
                    textControllerWidget(
                      context,
                      provider.descController,
                      "Description",
                      "Enter Description",
                      provider.updateDescription,
                      TextInputType.text,
                      false,
                      null,
                      focusNodes[9],
                      focusNodes[10],
                      TextInputAction.done,
                    ),
                    errorWidget(context, provider.descriptionError),
                    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(
                            "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: 5,
                              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,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                    SizedBox(height: 75),
                  ],
                ),
              ),
            ),
          ),
          floatingActionButtonLocation:
              FloatingActionButtonLocation.centerFloat,
          bottomNavigationBar: InkResponse(
            onTap:
                provider.submitClicked
                    ? null
                    : () {
                      provider.submitClicked = true;
                      provider.notifyListeners();
                      provider.addReceiptPaymentRequestionSubmitAPI(
                        context,
                        provider.formattedDateToSend,
                      );
                    },
            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,
                        ),
                      ),
            ),
          ),
        );
      },
    );
  }

  // void _showDialog(Widget child) {
  //   showCupertinoModalPopup<void>(
  //     context: context,
  //     builder:
  //         (BuildContext context) => Container(
  //       height: 216,
  //       padding: const EdgeInsets.only(top: 6.0),
  //       // The Bottom margin is provided to align the popup above the system
  //       // navigation bar.
  //       margin: EdgeInsets.only(
  //         bottom: MediaQuery.of(context).viewInsets.bottom,
  //       ),
  //       // Provide a background color for the popup.
  //       color: CupertinoColors.systemBackground.resolveFrom(context),
  //       // Use a SafeArea widget to avoid system overlaps.
  //       child: SafeArea(
  //         top: false,
  //         child: Column(
  //           children: [
  //             Expanded(
  //               flex: 1,
  //               child: SizedBox(
  //                 height: 40,
  //                 child: Row(
  //                   mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //                   children: [
  //                     // Add a Cancel button (optional)
  //                     CupertinoButton(
  //                       child: Text(
  //                         'Cancel',
  //                         style: TextStyle(fontFamily: "JakartaMedium"),
  //                       ),
  //                       onPressed: () {
  //                         Navigator.pop(context);
  //                       },
  //                     ),
  //                     // Add a Done button
  //                     CupertinoButton(
  //                       child: Text(
  //                         'Done',
  //                         style: TextStyle(fontFamily: "JakartaMedium"),
  //                       ),
  //                       onPressed: () {
  //                         Navigator.pop(context); // Dismiss the dialog
  //                       },
  //                     ),
  //                   ],
  //                 ),
  //               ),
  //             ),
  //             Expanded(flex: 3, child: child),
  //           ],
  //         ),
  //       ),
  //     ),
  //   );
  // }

  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<Paymentreceiptsprovider>(
                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"),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
