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

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

const MAX_EMAILS = 5;

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // simple email validation

const BillingEmails: React.FC<Props> = ({
  toggleSection,
  openSections,
  billingEmailsDisabled,
  handleBillingEmailsDisabled,
  values,
}) => {
  const { setSubmitting, setFieldValue } = useFormikContext();
  const [errors, setErrors] = useState<{ [key: number]: string }>({});

  // Live validation
  useEffect(() => {
    const newErrors: { [key: number]: string } = {};
    const emailSet = new Set<string>();

    values.billing_emails.forEach((email: string, index: number) => {
      const trimmed = email?.trim();
      if (!trimmed) {
        newErrors[index] = "Email cannot be empty";
      } else if (!emailRegex.test(trimmed)) {
        newErrors[index] = "Invalid email format";
      } else if (emailSet.has(trimmed)) {
        newErrors[index] = "Duplicate email not allowed";
      } else {
        emailSet.add(trimmed);
      }
    });

    setErrors(newErrors);
  }, [values.billing_emails]);

  const handleSave = async () => {
    if (Object.keys(errors).length > 0) return; // prevent save if any error
    try {
      setSubmitting(true);
      const payload = {
        billing_emails: values.billing_emails.filter((e: string) => e.trim() !== ""),
      };
      const response = await updateCustomerBillingEmails(payload);

      if (response?.status) {
        toast.success("Billing emails updated successfully");
        handleBillingEmailsDisabled();
      } else {
        toast.error(response?.message || "Failed to update billing emails");
      }
    } catch (err) {
      console.error(err);
      toast.error("Something went wrong");
    } finally {
      setSubmitting(false);
    }
  };

  const disableSave =
    billingEmailsDisabled || Object.keys(errors).length > 0 ||
    !values.billing_emails?.some((e: string) => e.trim() !== "");

  return (
    <div className="accordion-section mb-4">
      <div
        className="accordion-header"
        onClick={() => toggleSection("billingEmails")}
        style={{
          cursor: "pointer",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "1rem",
          background: "#fff",
          borderBottom: openSections.billingEmails ? "none" : "1px solid #eee",
        }}
      >
        <div className="d-float-center justify-content-start gap-lg-3 mb-0">
          <h4>Billing Emails</h4>
          {billingEmailsDisabled ? (
            <a
              href="#"
              onClick={(e) => {
                e.preventDefault();
                if (openSections?.billingEmails) e.stopPropagation();
                handleBillingEmailsDisabled();
              }}
            >
              <i className="fa fa-edit"></i> Edit
            </a>
          ) : (
            <button
              type="button"
              disabled={disableSave}
              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"></i> Save
            </button>
          )}
        </div>
        <i className={`fa ${openSections.billingEmails ? "fa-chevron-up" : "fa-chevron-down"}`}></i>
      </div>

      {openSections.billingEmails && (
        <div className="card card-style me-lg-0 package-info-card">
          <div className="content mb-0">
            <p className="mb-0">
              Add one or more billing emails where invoices and settlement reports will be sent.
            </p>
            <div className={`row mt-4 mb-0 ${billingEmailsDisabled ? "disabled-box" : "save-box"}`}>
              <FieldArray name="billing_emails">
                {({ remove, push }) => (
                  <>
                    {values.billing_emails.map((email: string, index: number) => (
                      <div key={index} className="input-style has-borders input-style-always-active validate-field mb-3 col-lg d-flex flex-column">
                        <div className="d-flex align-items-center">
                          <Field
                            type="email"
                            name={`billing_emails.${index}`}
                            className="form-control validate-text"
                            placeholder="Enter Billing Email"
                            disabled={billingEmailsDisabled}
                            onChange={(e: { target: { value: any; }; }) => setFieldValue(`billing_emails.${index}`, e.target.value)}
                          />
                          {!billingEmailsDisabled && (
                            <button
                              type="button"
                              className="btn btn-danger btn-sm ms-2"
                              onClick={() => remove(index)}
                            >
                              <i className="fa fa-trash"></i>
                            </button>
                          )}
                        </div>
                        {errors[index] && <div className="text-danger small mt-1">{errors[index]}</div>}
                      </div>
                    ))}

                    {!billingEmailsDisabled && values.billing_emails.length < MAX_EMAILS && (
                      <button type="button" className="btn btn-success btn-sm mt-2" onClick={() => push("")}>
                        <i className="fa fa-plus"></i> Add Email
                      </button>
                    )}

                    {values.billing_emails.length >= MAX_EMAILS && (
                      <small className="text-muted d-block mt-1">Maximum {MAX_EMAILS} emails allowed</small>
                    )}
                  </>
                )}
              </FieldArray>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default BillingEmails;
