import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:generp/Models/financeModels/addReceiptPaymentResponse.dart';
import 'package:provider/provider.dart';

import '../../Notifiers/financeProvider/paymentReceiptsProvider.dart';
import '../../Utils/app_colors.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> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var provider = Provider.of<Paymentreceiptsprovider>(
        context,
        listen: false,
      );
      provider.addReceiptPaymentRequestionViewAPI(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<Paymentreceiptsprovider>(
      builder: (context, provider, child) {
        return WillPopScope(
          child: Scaffold(
            backgroundColor: AppColors.white,
            appBar: appbar(context, "${widget.pageTitleName}"),
            body: Container(
              padding: EdgeInsets.symmetric(horizontal: 10),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20),
              ),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    TextWidget(context, "Account"),
                    DropdownButtonHideUnderline(
                      child: Row(
                        children: [
                          Expanded(
                            child: DropdownButton2<Accounts>(
                              isExpanded: true,
                              hint: Text(
                                'Select Account Type',
                                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,
                                      ),
                                    ),
                              )
                                  .toList(),
                              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.toString(),
                                    );
                                  }
                                }
                              },
                              buttonStyleData: ButtonStyleData(
                                height: 50,
                                width: 160,
                                padding: const EdgeInsets.only(
                                  left: 14,
                                  right: 14,
                                ),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(14),
                                  color: AppColors.text_field_color,
                                ),
                              ),
                              iconStyleData: const IconStyleData(
                                icon: Icon(Icons.keyboard_arrow_down),
                                iconSize: 12,
                                iconEnabledColor: Color(0xFF2D2D2D),
                                iconDisabledColor: Colors.grey,
                              ),
                              dropdownStyleData: DropdownStyleData(
                                maxHeight: 200,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(14),
                                  color: AppColors.text_field_color,
                                ),
                                scrollbarTheme: ScrollbarThemeData(
                                  radius: const Radius.circular(15),
                                  thickness: MaterialStateProperty.all<double>(
                                    6,
                                  ),
                                  thumbVisibility:
                                  MaterialStateProperty.all<bool>(true),
                                ),
                              ),
                              menuItemStyleData: const MenuItemStyleData(
                                height: 40,
                                padding: EdgeInsets.only(left: 14, right: 14),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    TextWidget(context, "Payment Account"),
                    DropdownButtonHideUnderline(
                      child: Row(
                        children: [
                          Expanded(
                            child: DropdownButton2<ReceiptAccounts>(
                              isExpanded: true,
                              hint: Text(
                                'Select Account Type',
                                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
                                              .toString(),
                                    );
                                  }
                                }
                              },
                              buttonStyleData: ButtonStyleData(
                                height: 50,
                                width: 160,
                                padding: const EdgeInsets.only(
                                  left: 14,
                                  right: 14,
                                ),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(14),
                                  color: AppColors.text_field_color,
                                ),
                              ),
                              iconStyleData: const IconStyleData(
                                icon: Icon(Icons.keyboard_arrow_down),
                                iconSize: 12,
                                iconEnabledColor: Color(0xFF2D2D2D),
                                iconDisabledColor: Colors.grey,
                              ),
                              dropdownStyleData: DropdownStyleData(
                                maxHeight: 200,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(14),
                                  color: AppColors.text_field_color,
                                ),
                                scrollbarTheme: ScrollbarThemeData(
                                  radius: const Radius.circular(15),
                                  thickness: MaterialStateProperty.all<double>(
                                    6,
                                  ),
                                  thumbVisibility:
                                  MaterialStateProperty.all<bool>(true),
                                ),
                              ),
                              menuItemStyleData: const MenuItemStyleData(
                                height: 40,
                                padding: EdgeInsets.only(left: 14, right: 14),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    textControllerWidget(
                      context,
                      provider.amountController,
                      "Enter Amount",
                      provider.updateAmount,
                    ),

                    ///payment date toBE
                    TextWidget(context, "Receipt Date"),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Expanded(
                          child: InkResponse(
                            onTap: () async {
                              provider.showDatePickerDialog(context);
                            },
                            child: Container(
                              padding: EdgeInsets.only(left: 10),
                              height:48,
                              alignment: Alignment.centerLeft,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(14),
                                  color: AppColors.text_field_color
                              ),
                              child: Text(
                                '${provider.formattedDate ?? 'Select Date'}',
                                style: TextStyle(
                                  fontSize: 14,
                                  fontFamily:
                                  "JakartaMedium",
                                  color: AppColors.semi_black,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    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
                                              .toString(),
                                    );
                                  }
                                }
                              },
                              buttonStyleData: ButtonStyleData(
                                height: 50,
                                width: 160,
                                padding: const EdgeInsets.only(
                                  left: 14,
                                  right: 14,
                                ),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(14),
                                  color: AppColors.text_field_color,
                                ),
                              ),
                              iconStyleData: const IconStyleData(
                                icon: Icon(Icons.keyboard_arrow_down),
                                iconSize: 12,
                                iconEnabledColor: Color(0xFF2D2D2D),
                                iconDisabledColor: Colors.grey,
                              ),
                              dropdownStyleData: DropdownStyleData(
                                maxHeight: 200,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(14),
                                  color: AppColors.text_field_color,
                                ),
                                scrollbarTheme: ScrollbarThemeData(
                                  radius: const Radius.circular(15),
                                  thickness: MaterialStateProperty.all<double>(
                                    6,
                                  ),
                                  thumbVisibility:
                                  MaterialStateProperty.all<bool>(true),
                                ),
                              ),
                              menuItemStyleData: const MenuItemStyleData(
                                height: 40,
                                padding: EdgeInsets.only(left: 14, right: 14),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    if ([
                      "Cheque",
                      "RTGS",
                      "IMPS",
                      "NEFT",
                    ].contains(provider.paymentModeValue)) ...
                    [
                      textControllerWidget(
                        context,
                        provider.bankNameController,
                        "Enter Bank Name",
                        provider.updateBankName,
                      ),

                      textControllerWidget(
                        context,
                        provider.bankBranchController,
                        "Enter Bank Branch",
                        provider.updateBankBranch,
                      ),

                      textControllerWidget(
                        context,
                        provider.bankAccNumberController,
                        "Enter Account Number",
                        provider.updateNumber,
                      ),

                      textControllerWidget(
                        context,
                        provider.bankIfscController,
                        "Enter Bank IFSC",
                        provider.updateIFSC,
                      ),

                      textControllerWidget(
                        context,
                        provider.bankAcHolderController,
                        "Enter Bank Account Holder Name",
                        provider.updateHolder,
                      ),
                    ] else if (provider.paymentModeValue == "UPI") ...
                    [
                      textControllerWidget(
                        context,
                        provider.amountController,
                        "Enter UPI ID",
                        provider.updateUPI,
                      ),
                    ],
                    textControllerWidget(
                      context,
                      provider.paymentReferenceController,
                      "Enter Payment Reference Number",
                      provider.updateDescription,
                    ),

                    textControllerWidget(
                      context,
                      provider.descController,
                      "Enter Description",
                      provider.updateDescription,
                    ),
                    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,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            floatingActionButtonLocation:
            FloatingActionButtonLocation.centerFloat,
            bottomNavigationBar: InkResponse(
              onTap: () {
                // provider.submitClicked = true;
                provider.addReceiptPaymentRequestionSubmitAPI(context, provider.formattedDate);
              },
              child: Container(
                height: 45,
                alignment: Alignment.center,
                margin: EdgeInsets.symmetric(horizontal: 10),
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                decoration: BoxDecoration(
                  color: AppColors.app_blue,
                  borderRadius: BorderRadius.circular(15),
                ),
                child: 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),
            ],
          ),
        ),
      ),
    );
  }
  Widget TextWidget(context, text) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 5.0, top: 8.0),
      child: Text(text),
    );
  }

  Widget ErrorWidget(context, text) {
    if (text != null)
      return Text(text!, style: TextStyle(color: Colors.red, fontSize: 12));
    else
      return SizedBox(height: 10);
  }

  Widget textControllerWidget(
      context,
      controller,
      hintText,
      Function(String)? onChanged,
      ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(bottom: 5.0, top: 8.0),
          child: Text(hintText),
        ),
        Container(
          height: hintText == "Enter Description" ? 150 : 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: controller,
              keyboardType: TextInputType.text,
              maxLines: hintText == "Enter Description" ? 60 : 1,
              onChanged: onChanged,
              decoration: InputDecoration(
                hintText: hintText,
                hintStyle: TextStyle(
                  fontWeight: FontWeight.w400,
                  color: Color(0xFFB4BEC0),
                  fontSize: 14,
                ),

                enabledBorder: InputBorder.none,
                focusedBorder: InputBorder.none,
              ),
            ),
          ),
        ),
      ],
    );
  }

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