import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/cupertino.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:intl/intl.dart';
import 'package:provider/provider.dart';

import '../../Models/financeModels/addDirectPaymentResponse.dart';

class Directpaymentrequesitionlist extends StatefulWidget {
  final String pageTitleName;

  const Directpaymentrequesitionlist({super.key, required this.pageTitleName});

  @override
  State<Directpaymentrequesitionlist> createState() =>
      _DirectpaymentrequesitionlistState();
}

class _DirectpaymentrequesitionlistState
    extends State<Directpaymentrequesitionlist> {
  Dropdowntheme ddtheme = Dropdowntheme();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var provider = Provider.of<Requestionlistprovider>(
        context,
        listen: false,
      );
      provider.addDirectPaymentRequestionViewAPI(context);
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

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

  @override
  Widget build(BuildContext context) {
    return Consumer<Requestionlistprovider>(
      builder: (context, provider, child) {
        return WillPopScope(
          child: Scaffold(
            resizeToAvoidBottomInset: true,
            backgroundColor: AppColors.white,
            appBar: appbar(context, "${widget.pageTitleName}"),
            body: SafeArea(
              child: 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"),
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<DirectAccounts>(
                                isExpanded: true,
                                hint: Text(
                                  'Select Account',
                                  style: TextStyle(fontSize: 14),
                                  overflow: TextOverflow.ellipsis,
                                ),
                                items:
                                    provider.directAccounts
                                        .map(
                                          (accs) =>
                                              DropdownMenuItem<DirectAccounts>(
                                                value: accs,
                                                child: Text(
                                                  accs.name ?? '',
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                  overflow: TextOverflow.ellipsis,
                                                ),
                                              ),
                                        )
                                        .toList(),
                                value: provider.selectDirectAccounts,
                                onChanged: (DirectAccounts? value) {
                                  if (value != null) {
                                    if (provider.directAccounts.isNotEmpty) {
                                      provider.selectDirectAccounts = value;
                                      print(
                                        "Selected Complaint Type: ${value.name}, ID: ${value.id}",
                                      );
                                      provider.directAccountId = value.id!;
                                      provider.directAccountValue = value.name!;
                                      print(
                                        "hfjkshfg" +
                                            provider.directAccountId.toString(),
                                      );
                                    }
                                  }
                                },
                                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.selectDirectAccountError),
                      TextWidget(context, "Payment Account"),
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<DirectPaymentAccounts>(
                                isExpanded: true,
                                hint: Text(
                                  'Select Account Type',
                                  style: TextStyle(fontSize: 14),
                                  overflow: TextOverflow.ellipsis,
                                ),
                                items:
                                    provider.directPaymentAccounts
                                        .map(
                                          (accs) => DropdownMenuItem<
                                            DirectPaymentAccounts
                                          >(
                                            value: accs,
                                            child: Text(
                                              accs.name ?? '',
                                              style: const TextStyle(
                                                fontSize: 14,
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                        )
                                        .toList(),
                                value: provider.selectDirectPaymentAccounts,
                                onChanged: (DirectPaymentAccounts? value) {
                                  if (value != null) {
                                    if (provider
                                        .directPaymentAccounts
                                        .isNotEmpty) {
                                      provider.selectDirectPaymentAccounts =
                                          value;
                                      print(
                                        "Selected Complaint Type: ${value.name}, ID: ${value.id}",
                                      );
                                      provider.directPaymentAccountsID =
                                          value.id!;
                                      provider.directPaymentAccountsValue =
                                          value.name!;
                                      print(
                                        "hfjkshfg" +
                                            provider.directPaymentAccountsID
                                                .toString(),
                                      );
                                    }
                                  }
                                },
                                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.selectDirectPaymentAccountError,
                      ),
                      textControllerWidget(
                        context,
                        provider.amountController,
                        "Enter Amount",
                        provider.updateAmount,TextInputType.number,false,FilteringTextInputFormatter.digitsOnly
                      ),
                      errorWidget(context, provider.amountError),
              
                      ///payment date toBE
                      TextWidget(context, "Enter 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) {},
                                    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<DirectPaymentModes>(
                                isExpanded: true,
                                hint: Text(
                                  'Select Payment mode',
                                  style: TextStyle(fontSize: 14),
                                  overflow: TextOverflow.ellipsis,
                                ),
                                items:
                                    provider.directPaymentModes
                                        .map(
                                          (paymenents) => DropdownMenuItem<
                                            DirectPaymentModes
                                          >(
                                            value: paymenents,
                                            child: Text(
                                              paymenents.name ?? '',
                                              style: const TextStyle(
                                                fontSize: 14,
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                        )
                                        .toList(),
                                value: provider.selectDirectPaymentModes,
                                onChanged: (DirectPaymentModes? value) {
                                  if (value != null) {
                                    if (provider.directPaymentModes.isNotEmpty) {
                                      provider.selectDirectPaymentModes = value;
                                      print(
                                        "Selected Complaint Type: ${value.name}, ID: ${value.id}",
                                      );
                                      provider.directPaymentModesID = value.id!;
                                      provider.directPaymentModesValues =
                                          value.name!;
                                      print(
                                        "hfjkshfg" +
                                            provider.directPaymentModesID
                                                .toString(),
                                      );
                                    }
                                  }
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),
                      errorWidget(context, provider.selectDirectPaymentError),
                      if ([
                        "Cheque",
                        "RTGS",
                        "IMPS",
                        "NEFT",
                      ].contains(provider.directPaymentModesValues)) ...[
                        textControllerWidget(
                          context,
                          provider.bankNameController,
                          "Enter Bank Name",
                          provider.updateBankName,TextInputType.text,false,null
                        ),
                        errorWidget(context, provider.bankNameError),
                        textControllerWidget(
                          context,
                          provider.bankBranchController,
                          "Enter Bank Branch",
                          provider.updateBankBranch,TextInputType.text,false,null
                        ),
                        errorWidget(context, provider.bankBranchError),
                        textControllerWidget(
                          context,
                          provider.bankAccNumberController,
                          "Enter Account Number",
                          provider.updateNumber,TextInputType.number,false,FilteringTextInputFormatter.digitsOnly
                        ),
                        errorWidget(context, provider.bankNumberError),
                        textControllerWidget(
                          context,
                          provider.bankIfscController,
                          "Enter Bank IFSC",
                          provider.updateIFSC,TextInputType.text,false,null
                        ),
                        errorWidget(context, provider.bankIFSCError),
                        textControllerWidget(
                          context,
                          provider.bankAcHolderController,
                          "Enter Bank Account Holder Name",
                          provider.updateHolder,TextInputType.text,false,null
                        ),
                        errorWidget(context, provider.bankHolderError),
                      ] else if (provider.directPaymentModesValues == "UPI") ...[
                        textControllerWidget(
                          context,
                          provider.bankUpiController,
                          "Enter UPI ID",
                          provider.updateUPI,TextInputType.text,false,null
                        ),
                        errorWidget(context, provider.UPIError),
                      ],
                      textControllerWidget(
                        context,
                        provider.paymentReferenceController,
                        "Enter Payment Reference Number",
                        provider.updateReference,TextInputType.text,false,null
                      ),
                      errorWidget(context, provider.paymentreferenceerror),
                      textControllerWidget(
                        context,
                        provider.descController,
                        "Enter Description",
                        provider.updateDescription,TextInputType.text,false,null
                      ),
                      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: [
                              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.addDirectPaymentRequestionSubmitAPI(
                  context,
                  provider.formattedDate,
                );
              },
              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(AppColors.app_blue),
                ): Text(
                  "Submit",
                  style: TextStyle(
                    fontSize: 15,
                    fontFamily: "JakartaMedium",
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
          onWillPop: () {
            provider.resetForm();
            return onBackPressed(context);
          },
        );
      },
    );
  }

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