import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Notifiers/PaymentDetailsProvider.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:provider/provider.dart';

import '../../Models/TechnicianLoadNumbersResponse.dart';
import '../../Utils/dropdownTheme.dart';

class Paymentdetails extends StatefulWidget {
  final accountName, referenceID, name, genId;

  const Paymentdetails({
    super.key,
    required this.accountName,
    required this.name,
    required this.genId,
    required this.referenceID,
  });

  @override
  State<Paymentdetails> createState() => _PaymentdetailsState();
}

class _PaymentdetailsState extends State<Paymentdetails> {
  Dropdowntheme ddtheme = Dropdowntheme();
  TextEditingController Amountcontroller = TextEditingController();
  TextEditingController Referencecontroller = TextEditingController();
  TextEditingController nameController = TextEditingController();
  TextEditingController designationController = TextEditingController();
  TextEditingController mobController = TextEditingController();
  TextEditingController altMobController = TextEditingController();
  TextEditingController telController = TextEditingController();
  TextEditingController emailController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Future.microtask(() {
        var provider = Provider.of<Paymentdetailsprovider>(
          context,
          listen: false,
        );
        provider.LoadNumbersAPI(
            context, widget.accountName, widget.referenceID, widget.genId);
      },);
    },);
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<Paymentdetailsprovider>(
        builder: (context, provider, child) {
          // Debug prints to inspect contactsDropDown and selectContact
          debugPrint("contactsDropDown: ${provider.contactsDropDown}");
          debugPrint("selectContact: ${provider.selectContact}");
          return WillPopScope(
            onWillPop: () => onBackPressed(context),
            child: Scaffold(

              resizeToAvoidBottomInset: true,
              appBar: appbar(context, "Payment Details"),
              backgroundColor: AppColors.scaffold_bg_color,
              body: SafeArea(
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                  margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(20)
                  ),
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                            padding: EdgeInsets.symmetric(vertical: 5),
                            child: Text("${widget.name}",
                              style: TextStyle(
                                  fontFamily: "JakartaMedium",
                                  color: AppColors.app_blue),)),
                        SizedBox(height: 10,),
                        Padding(
                          padding: const EdgeInsets.only(bottom: 5.0),
                          child: Text("Phone Number"),
                        ),
                        DropdownButtonHideUnderline(
                          child: Row(
                            children: [
                              Expanded(
                                child: DropdownButton2<Contacts>(
                                  isExpanded: true,
                                  hint: const Row(
                                    children: [
                                      Expanded(
                                        child: Text(
                                          'Select Phone Number',
                                          style: TextStyle(
                                            fontSize: 14,
                                          ),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                    ],
                                  ),
                                  items: [
                                    ...provider.contactsDropDown.map((contacts) {
                                      return DropdownMenuItem<Contacts>(
                                        value: contacts,
                                        // You can use the entire object, but we need to ensure it's unique
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment
                                              .start,
                                          children: [
                                            Text(
                                              contacts.name ?? "",
                                              maxLines: 1,
                                              style: const TextStyle(
                                                fontSize: 12,
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                            Text(
                                              contacts.mob1 ?? "",
                                              style: const TextStyle(
                                                fontSize: 12,
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ],
                                        ),
                                      );
                                    }).toList(),
                                    DropdownMenuItem<Contacts>(
                                      value: null,
                                      // No value associated with the button
                                      enabled: false,
                                      // To disable selecting this item
                                      child: InkWell(
                                        onTap: () {
                                          _addContactSheet(context);
                                        },
                                        child: Container(
                                          decoration: BoxDecoration(
                                            border: Border.all(
                                              color: AppColors.app_blue,
                                              width: 0.5
                                            ),
                                            borderRadius: BorderRadius.circular(12)
                                          ),
                                          padding: const EdgeInsets.symmetric(
                                              vertical: 12, horizontal: 14),
                                          child: Row(
                                            mainAxisAlignment: MainAxisAlignment
                                                .center,
                                            children: const [
                
                                              Text(
                                                'Add Contact',
                                                style: TextStyle(fontSize: 14,
                                                    color: Colors.blue),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                  value: provider.selectContact,
                                  // The selected value is now the entire 'Contacts' object
                                  onChanged: (Contacts? value) {
                                    if (value != null) {
                                      if (provider.contactsDropDown.isNotEmpty) {
                                        provider.selectContact =
                                            value; // Set the selected contact
                                        provider.contact = value.name ??
                                            ""; // Update the contact name
                                        provider.contactID = value.mob1 ??
                                            ""; // Update the contact ID
                                        debugPrint("Selected Contact: ${value
                                            .name}, Phone: ${value.mob1}");
                                      }
                                    }
                                  },
                                  buttonStyleData: ddtheme.buttonStyleData,
                                  iconStyleData: ddtheme.iconStyleData,
                                  menuItemStyleData: ddtheme.menuItemStyleData,
                                  dropdownStyleData: ddtheme.dropdownStyleData,
                                ),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(height: 10,),
                        Padding(
                          padding: const EdgeInsets.only(bottom: 5.0),
                          child: Text("Complaint Type"),
                        ),
                        DropdownButtonHideUnderline(
                          child: Row(
                            children: [
                              Expanded(
                                child: DropdownButton2<PaymentModeList>(
                                  isExpanded: true,
                                  hint: const Row(
                                    children: [
                                      Expanded(
                                        child: Text(
                                          'Select Complaint Type',
                                          style: TextStyle(
                                            fontSize: 14,
                                          ),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                    ],
                                  ),
                                  items: provider.paymentModeDropDown
                                      .map((paymentMode) =>
                                      DropdownMenuItem<PaymentModeList>(
                                        value: paymentMode,
                                        child: Text(
                                          paymentMode.name ?? '',
                                          style: const TextStyle(
                                            fontSize: 14,
                                          ),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ))
                                      .toList(),
                                  value: provider.selectPaymentMode,
                                  onChanged: (PaymentModeList? value) {
                                    if (value != null) {
                                      if (provider.paymentModeDropDown.isNotEmpty) {
                                        provider.selectPaymentMode = value;
                                        print(
                                            "Selected Complaint Type: ${value
                                                .name}, ID: ${value.id}");
                                        provider.PaymentMode = value?.name;
                                        provider.paymentModeID = value?.id;
                                        print("hfjkshfg" +
                                            provider.paymentModeID.toString());
                                      }
                                    }
                                  },
                                  buttonStyleData: ddtheme.buttonStyleData,
                                  iconStyleData: ddtheme.iconStyleData,
                                  menuItemStyleData: ddtheme.menuItemStyleData,
                                  dropdownStyleData: ddtheme.dropdownStyleData,
                                ),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(height: 10,),
                        Padding(
                          padding: const EdgeInsets.only(bottom: 5.0),
                          child: Text("Amount"),
                        ),
                        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:
                              Amountcontroller,
                              keyboardType:
                              TextInputType.text,
                              decoration: InputDecoration(
                
                                hintText:
                                "Enter Amount",
                                hintStyle: TextStyle(
                                    fontWeight: FontWeight.w400,
                                    color: Color(0xFFB4BEC0),
                                    fontSize: 14
                                ),
                
                                enabledBorder:
                                InputBorder.none,
                                focusedBorder:
                                InputBorder.none,
                              ),
                
                            ),
                          ),
                        ),
                        SizedBox(height: 10,),
                        Padding(
                          padding: const EdgeInsets.only(bottom: 5.0),
                          child: Text("Reference Number"),
                        ),
                        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:
                              Referencecontroller,
                              keyboardType:
                              TextInputType.text,
                              decoration: InputDecoration(
                
                                hintText:
                                "Enter Reference Number",
                                hintStyle: TextStyle(
                                    fontWeight: FontWeight.w400,
                                    color: Color(0xFFB4BEC0),
                                    fontSize: 14
                                ),
                
                                enabledBorder:
                                InputBorder.none,
                                focusedBorder:
                                InputBorder.none,
                              ),
                
                            ),
                          ),
                        ),
                        SizedBox(height: 10,),
                        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("Scan Document", 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,
              floatingActionButton: InkWell(
                onTap: () {
                  provider.CheckValidations(
                      context, Referencecontroller.text, Amountcontroller.text);
                  if (provider.CollectionId != 0) {
                    _showOTPSheetSheet(context);
                  }
                },
                child: Container(
                  alignment: Alignment.center,
                  height: 45,
                  margin: EdgeInsets.only(
                    left: 5.0,
                    right: 5.0,
                    top: 5.0,
                    bottom: 5.0,
                  ),
                  decoration: BoxDecoration(
                    color: AppColors.app_blue, //1487C9
                    borderRadius: BorderRadius.circular(15.0),
                  ),
                  child: Center(
                    child: Text(
                      "Send OTP",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 15,
                          fontFamily: "JakartaMedium",
                          color: Colors.white),
                    ),
                  ),
                ),
              ),
            ),
          );
        });
  }

  Future<void> _showAttachmentSheet(BuildContext context) {
    return showModalBottomSheet(
      useSafeArea: true,
      isDismissible: true,
      isScrollControlled: true,
      showDragHandle: true,
      backgroundColor: Colors.white,
      enableDrag: true,
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return SafeArea(
              child: Consumer<Paymentdetailsprovider>(
                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,
                                    fontSize: 16
                                ),
                              ),
                            ),
                            SizedBox(height: 15,),
                            InkWell(
                              onTap: () {
                                Navigator.of(context).pop(false);
                                provider.imgFromGallery(
                                    context, Referencecontroller.text,
                                    Amountcontroller.text);
                              },
                              child: Container(
                                height: 35,
                                child: Text("Select photo from gallery"),
                              ),
                            ),
                            SizedBox(height: 10),
                            InkWell(
                              onTap: () {
                                Navigator.of(context).pop(false);
                                provider.imgFromCamera(
                                    context, Referencecontroller.text,
                                    Amountcontroller.text);
                              },
                              child: Container(
                                height: 35,
                                child: Text("Capture photo from camera"),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }


  Future<void> _showOTPSheetSheet(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<Paymentdetailsprovider>(
                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(
                                "Enter OTP",
                                style: TextStyle(
                                    color: AppColors.app_blue,
                                    fontSize: 16
                                ),
                              ),
                            ),
                            SizedBox(height: 15,),
                            Column(
                              children: [
                                Container(
                                  alignment: Alignment.center,

                                  height: 50,
                                  margin: EdgeInsets.only(
                                      left: 5.0, right: 5.0),
                                  child: PinCodeTextField(

                                    appContext: context,
                                    pastedTextStyle: TextStyle(
                                      fontWeight: FontWeight.bold,
                                    ),
                                    length: 4,
                                    blinkWhenObscuring: true,

                                    animationType: AnimationType.fade,
                                    // validator: (v) {
                                    //   if (v!.length < 3) {
                                    //     return "I'm from validator";
                                    //   } else {
                                    //     return null;
                                    //   }
                                    // },
                                    pinTheme: PinTheme(
                                      shape: PinCodeFieldShape.underline,
                                      borderRadius: BorderRadius.circular(16),
                                      fieldHeight: 60,
                                      fieldWidth: 60,
                                      activeFillColor: AppColors
                                          .text_field_color,
                                      activeColor: AppColors.app_blue,
                                      selectedColor: AppColors.text_field_color,
                                      selectedFillColor: AppColors
                                          .text_field_color,
                                      inactiveFillColor: AppColors
                                          .text_field_color,
                                      inactiveColor: AppColors.text_field_color,
                                      fieldOuterPadding: EdgeInsets.only(
                                        left: 5,
                                        right: 5,
                                      ),
                                      inactiveBorderWidth: 0,
                                      activeBorderWidth: 0.5,
                                    ),
                                    enableActiveFill: true,
                                    keyboardType: TextInputType.number,
                                    boxShadows: const [
                                      BoxShadow(
                                        offset: Offset(0, 1),
                                        color: Colors.black12,
                                        blurRadius: 10,
                                      ),
                                    ],
                                    onCompleted: (String enteredCode) {
                                      provider.enteredOtp = enteredCode;
                                      // clearText = true;
                                      provider.OTPVerifyAPI(context);
                                      Navigator.pop(context, true);

                                      debugPrint("Completed");
                                    },
                                    // onTap: () {
                                    //   print("Pressed");
                                    // },
                                    onChanged: (String enteredCode) {
                                      debugPrint(enteredCode);

                                      provider.enteredOtp = enteredCode;
                                    },
                                    onSubmitted: (String enteredCode) {
                                      provider.enteredOtp = enteredCode;
                                      // clearText = true;
                                      // Verify_otp();
                                    },
                                    enablePinAutofill: true,
                                    useExternalAutoFillGroup: true,
                                    beforeTextPaste: (text) {
                                      debugPrint("Allowing to paste $text");
                                      //if you return true then it will show the paste confirmation dialog. Otherwise if false, then nothing will happen.
                                      //but you can show anything you want here, like your pop up saying wrong paste format or etc
                                      return true;
                                    },
                                  ),
                                ),
                                SizedBox(height: 15),
                                Container(
                                  width: 110,
                                  height: 45,
                                  margin: EdgeInsets.only(
                                      left: 10.0, right: 10.0),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(15.0),
                                  ),
                                  child: TextButton(
                                    onPressed:
                                        () =>
                                    {
                                      Navigator.of(context).pop(false),
                                      provider.OTPVerifyAPI(context),
                                    },
                                    child: Text(
                                      "Submit",
                                      style: TextStyle(
                                          fontWeight: FontWeight.w300),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }

  Future<void> _addContactSheet(BuildContext context) {
    final controllers = [
      nameController,
      designationController,
      mobController,
      altMobController,
      telController,
      emailController
    ];
    final controllersNames = [
      "Name",
      "Designation",
      "Mobile Number",
      "Alternate Mobile Number",
      "Telephone Number",
      "Email ID"
    ];

    final hintTextNames = [
      "Enter Name",
      "Enter Designation",
      "Enter Mobile Number",
      "Enter Alternate Mobile Number",
      "Enter Telephone Number",
      "Enter Email ID"
    ];
    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<Paymentdetailsprovider>(
                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: [
                            SizedBox(height: 15),
                            Align(
                              alignment: Alignment.center,
                              child: Text(
                                "Add Contact",
                                style: TextStyle(
                                    color: AppColors.app_blue,
                                    fontSize: 16
                                ),
                              ),
                            ),

                            ...List.generate(controllers.length, (index) {


                              return Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    "${controllersNames[index]}",

                                  ),
                                  Container(
                                    height: 50,

                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                      color: AppColors.text_field_color,
                                      borderRadius:
                                      BorderRadius.circular(25),
                                    ),
                                    child: Padding(
                                      padding:
                                      const EdgeInsets.fromLTRB(
                                          10.0, 0.0, 10, 0),
                                      child: TextFormField(
                                        controller:
                                        controllers[index],
                                        keyboardType:
                                        TextInputType.text,
                                        decoration: InputDecoration(

                                          hintText:
                                          "${hintTextNames[index]}",
                                          hintStyle: TextStyle(
                                              fontWeight: FontWeight.w400,
                                              color: Color(0xFFB4BEC0),
                                              fontSize: 14
                                          ),

                                          enabledBorder:
                                          InputBorder.none,
                                          focusedBorder:
                                          InputBorder.none,
                                        ),

                                      ),
                                    ),
                                  ),
                                ],
                              );
                            },),

                            InkWell(
                              onTap: () {
                                provider.AddContactAPIFunction(
                                    context,
                                    widget.accountName,
                                    widget.genId,
                                    nameController.text,
                                    designationController.text,
                                    mobController.text,
                                    altMobController.text,
                                    telController.text,
                                emailController.text);
                              },
                              child: Container(
                                alignment: Alignment.center,
                                height: 45,
                                margin: EdgeInsets.only(
                                  left: 5.0,
                                  right: 5.0,
                                  top: 5.0,
                                  bottom: 5.0,
                                ),
                                decoration: BoxDecoration(
                                  color: AppColors.app_blue, //1487C9
                                  borderRadius: BorderRadius.circular(30.0),
                                ),
                                child: Center(
                                  child: Text(
                                    "Submit",
                                    textAlign: TextAlign.center,
                                    style: TextStyle(color: Colors.white),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}
