/* eslint-disable @typescript-eslint/no-explicit-any */
import React from "react";
import { Field, ErrorMessage, useFormikContext } from "formik";
import { updateCustomerBillingAddress } from "../../../../Api/CustomerApi";
import { toast } from "react-toastify";

interface Props {
  toggleSection: (section: string) => void;
  openSections: { [key: string]: boolean };
  billingAddressDisabled: boolean;
  handleBillingAddressDisabled: () => void;
  values: any;
}

const BillingAddress: React.FC<Props> = ({
  toggleSection,
  openSections,
  billingAddressDisabled,
  handleBillingAddressDisabled,
  values,
}) => {
  const { setSubmitting } = useFormikContext();

  const handleSave = async () => {
    try {
      setSubmitting(true);
      const payload = { billing_address: values.billing_address };

      const response = await updateCustomerBillingAddress(payload);

      if (response?.status) {
        toast.success("Billing address updated successfully");
        handleBillingAddressDisabled(); // disable again after save
      } else {
        toast.error(response?.message || "Failed to update billing address");
      }
    } catch (error) {
      console.error("Billing address update failed:", error);
      toast.error("Something went wrong");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="accordion-section mb-4 mt-4">
      <div
        className="accordion-header"
        onClick={() => toggleSection("billingAddress")}
        style={{
          cursor: "pointer",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "1rem",
          background: "#fff",
          borderBottom: openSections.billingAddress ? "none" : "1px solid #eee",
        }}
      >
        <div className="d-float-center justify-content-start gap-lg-3 mb-0">
          <h4>Billing Address</h4>
          {billingAddressDisabled ? (
            <a
              href="#"
              onClick={(e) => {
                e.preventDefault();
                if (openSections?.billingAddress) e.stopPropagation();
                handleBillingAddressDisabled();
              }}
            >
              <i className="fa fa-edit" aria-hidden="true"></i> Edit
            </a>
          ) : (
            <button
              type="button"
              onClick={handleSave}
              className="close-menu btn btn-m shadow-l rounded-s font-600 delybell-primary mt-0 font-16"
            >
              <i className="fa fa-save" aria-hidden="true"></i> Save
            </button>
          )}
        </div>
        <i
          className={`fa ${
            openSections.billingAddress ? "fa-chevron-up" : "fa-chevron-down"
          }`}
        ></i>
      </div>

      {openSections.billingAddress && (
        <div className="card card-style me-lg-0 package-info-card">
          <div className="content mb-0">
            <p className="mb-0">
              Set your default billing address for invoice and settlement purposes.
            </p>
            <div
              className={`row mt-4 mb-0 ${
                billingAddressDisabled ? "disabled-box" : "save-box"
              }`}
            >
              <div className="input-style has-borders no-icon input-style-always-active validate-field mb-4 col-lg">
                <Field
                  as="textarea"
                  name="billing_address"
                  className="form-control validate-text"
                  placeholder="Enter Billing Address"
                  disabled={billingAddressDisabled}
                  rows={3}
                  maxLength={255}
                />
                <label htmlFor="billing_address" className="color-highlight">
                  Billing Address
                </label>
                <div className="d-flex justify-content-end">
                  <small className="text-muted">
                    {255 - (values?.billing_address?.length || 0)} characters remaining
                  </small>
                </div>
                <ErrorMessage
                  name="billing_address"
                  component="div"
                  className="text-danger small"
                />
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default BillingAddress;
