import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/financeProvider/RequestionListProvider.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:provider/provider.dart';

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

class Submitpaymentrequestionlistsbymode extends StatefulWidget {
  final String mode;
  final String pageTitleName;
  const Submitpaymentrequestionlistsbymode({super.key, required this.mode,required this.pageTitleName});

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


class _SubmitpaymentrequestionlistsbymodeState
    extends State<Submitpaymentrequestionlistsbymode> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
     var  provider = Provider.of<Requestionlistprovider>(context, listen: false);
      provider.addPaymentRequestionViewAPI(context, widget.mode);
    });
  }

  @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) {
        WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
          if (widget.mode == "self" && provider.accounts.length == 1) {
            provider.selectedAccount = provider.accounts.first;
            provider.accountId = provider.accounts.first.id!;
          }
        });
        return WillPopScope(
          child: Scaffold(
            resizeToAvoidBottomInset: true,
            backgroundColor: AppColors.white,
            appBar: appbar2(context, "${widget.pageTitleName}",provider.resetForm,SizedBox(width: 0,)),
            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, "Select 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.accounts
                                        .map(
                                          (accs) => DropdownMenuItem<Accounts>(
                                            value: accs,
                                            child: Text(
                                              accs.name ?? '',
                                              style: const TextStyle(
                                                fontSize: 14,
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                        )
                                        .toList(),
                                value: provider.selectedAccount,
                                onChanged:
                                    (widget.mode == "self" &&
                                            provider.accounts.length == 1)
                                        ? null
                                        : (Accounts? value) {
                                          if (value != null) {
                                            if (provider.accounts.isNotEmpty) {
                                              provider.selectedAccount = value;
                                              print(
                                                "Selected Complaint Type: ${value.name}, ID: ${value.id}",
                                              );
                                              provider.accountId = value.id!;
                                              print(
                                                "hfjkshfg" +
                                                    provider.accountId.toString(),
                                              );
                                            }
                                          }
                                        },
                                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:  IconStyleData(
                                  icon:  SvgPicture.asset("assets/svg/arrow_dropdown.svg",height: 25,width: 20,),
                                  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),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      errorWidget(context, provider.selectAccountError),
              
                      if (["self", "admin"].contains(widget.mode)) ...[
                        TextWidget(context, "Select Requisition Type"),
                        DropdownButtonHideUnderline(
                          child: Row(
                            children: [
                              Expanded(
                                child: DropdownButton2<String>(
                                  isExpanded: true,
                                  hint: Text(
                                    'Select Request Type',
                                    style: TextStyle(fontSize: 14),
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  items:
                                      provider.requestingPurposes
                                          .map(
                                            (accs) => DropdownMenuItem<String>(
                                              value: accs,
                                              child: Text(
                                                accs ?? '',
                                                style: const TextStyle(
                                                  fontSize: 14,
                                                ),
                                                overflow: TextOverflow.ellipsis,
                                              ),
                                            ),
                                          )
                                          .toList(),
                                  value: provider.selectReqPurpose,
              
                                  onChanged: (String? value) {
                                    if (value != null) {
                                      provider.selectReqPurpose = value;
                                      print("Selected Complaint Type: ${value},");
              
                                      print(
                                        "hfjkshfg" +
                                            provider.selectReqPurpose.toString(),
                                      );
                                    }
                                  },
                                  buttonStyleData: 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:  IconStyleData(
                                    icon: SvgPicture.asset("assets/svg/arrow_dropdown.svg",height: 25,width: 20,),
                                    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),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ] else ...[
                        textControllerWidget(
                          context,
                          provider.reqPurposeController,
                          "Enter Request Purpose",
                          provider.updateReqPupose,TextInputType.text,false,null
                        ),
                      ],
                      errorWidget(context, provider.reqPurposeError),
              
                      textControllerWidget(
                        context,
                        provider.descController,
                        "Enter Description",
                        provider.updateDescription,TextInputType.text,false,null
                      ),
                      errorWidget(context, provider.descriptionError),
              
                      textControllerWidget(
                        context,
                        provider.amountController,
                        "Enter Amount",
                        provider.updateAmount,TextInputType.number,false,FilteringTextInputFormatter.digitsOnly
                      ),
                      errorWidget(context, provider.amountError),
              
                      TextWidget(context, "Select Payment Mode"),
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<PaymentModes>(
                                isExpanded: true,
                                hint: Text(
                                  'Select Payment mode',
                                  style: TextStyle(fontSize: 14),
                                  overflow: TextOverflow.ellipsis,
                                ),
                                items:
                                    provider.paymentModes
                                        .map(
                                          (paymenents) =>
                                              DropdownMenuItem<PaymentModes>(
                                                value: paymenents,
                                                child: Text(
                                                  paymenents.name ?? '',
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                  ),
                                                  overflow: TextOverflow.ellipsis,
                                                ),
                                              ),
                                        )
                                        .toList(),
                                value: provider.selectedPayment,
                                onChanged: (PaymentModes? value) {
                                  if (value != null) {
                                    if (provider.paymentModes.isNotEmpty) {
                                      provider.selectedPayment = value;
                                      print(
                                        "Selected Complaint Type: ${value.name}, ID: ${value.id}",
                                      );
                                      provider.paymentModeId = value.id!;
                                      provider.paymentModeValue = value.name!;
                                      print(
                                        "hfjkshfg" +
                                            provider.paymentModeId.toString(),
                                      );
                                    }
                                  }
                                },
                                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:  IconStyleData(
                                  icon:  SvgPicture.asset("assets/svg/arrow_dropdown.svg",height: 25,width: 20,),
                                  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),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      errorWidget(context, provider.selectPaymentError),
              
                      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,))
                            ],
                          ),
                        )
                      ],
                      errorWidget(context, provider.FileError),
              
                      if ([
                        "Cheque",
                        "RTGS",
                        "IMPS",
                        "NEFT",
                      ].contains(provider.paymentModeValue)) ...[
                        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.paymentModeValue == "UPI") ...[
                        textControllerWidget(
                          context,
                          provider.amountController,
                          "Enter UPI ID",
                          provider.updateUPI,TextInputType.text,false,null
                        ),
                        errorWidget(context, provider.UPIError),
                      ],
                    ],
                  ),
                ),
              ),
            ),
            floatingActionButtonLocation:
                FloatingActionButtonLocation.centerFloat,
            bottomNavigationBar: InkResponse(
              onTap:provider.submitClicked?null: () {
                        provider.submitClicked = true;
                        provider.addPaymentRequestionSubmitAPI(
                          context,
                          widget.mode,
                        );
                      },
              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: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);
          },
        );
      },
    );
  }


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