import React, { useEffect, useState } from "react";
import { emailRules } from "@/utils/regex/regex";

const CustomSendEmail = (props: any) => {
  const [otherEmailInputValue, setOtherEmailInputValue] = useState<any>("");
  const [otherEmailsValues, setOtherEmailsValues] = useState<any>([]);
  const [otherEmailError, setOtherEmailError] = useState("");

  const handleChangeOtherEmails = (event: any) => {
    setOtherEmailInputValue(event.target.value);
    setOtherEmailError("");
  };



  const isValidEmail = (emailString: string) => {
    const emailRegex = emailRules;
    // Split by commas, spaces, or semicolons and trim each email, removing trailing periods
    const emails = emailString.split(/[,\s;]+/).map((email: string) => email.trim().replace(/\.+$/, ''));
    
    // Check if every email in the array is valid
    return emails.every((email: string) => emailRegex.test(email));
  };

  const handleKeyPressOtherEmails = (event: any) => {
    if (event.key === "Enter") {
      if (otherEmailInputValue.trim() === "") {
        setOtherEmailError("Email cannot be empty");
      } else if (isValidEmail(otherEmailInputValue)) {

        const emailArray = otherEmailInputValue
      .split(/[,\s;]+/) // Split by commas, spaces, or semicolons
      .map((email: string) => email.trim().replace(/\.+$/, '')) // Trim each email and remove all trailing periods
      .filter((email: string) => isValidEmail(email)); // Filter out invalid emails
    
        setOtherEmailsValues((prevValues: string[]) => [
          ...prevValues,
          ...emailArray,  // Spread the emailArray to add each email individually
        ]);
        setOtherEmailInputValue("");
        setOtherEmailError("");
      } else {
        setOtherEmailError("Please enter a valid email address");
      }
    }
  };

  const handleRemoveOtherEmails = (id: number) => {
    setOtherEmailsValues((prevValues: any[]) =>
      prevValues.filter((item, index) => index !== id),
    );
  };

  useEffect(() => {
    props.handleChangeDrop(
      props.carrierIndex,
      "other_emails",
      otherEmailsValues,
      props?.carrierInfo?.carrier_id,
    );
  }, [otherEmailsValues, otherEmailInputValue]);

  useEffect(() => {
    if (props?.carrierInfo?.optional_emails?.length > 0) {
      setOtherEmailsValues(props?.carrierInfo?.optional_emails);
    }
  }, [props?.carrierInfo]);

  return (
    <div>
      <input
        value={otherEmailInputValue}
        onChange={handleChangeOtherEmails}
        onKeyPress={handleKeyPressOtherEmails}
        type="text"
        className="form-field"
        placeholder="Enter Email"
      />
      {otherEmailError && <div style={{ color: "red" }}>{otherEmailError}</div>}
      {otherEmailsValues?.length > 0 && (
        <div
          className="d-flex flex-wrap p-2 gap-1"
          style={{ background: "#f3f3f3" }}
        >
          {otherEmailsValues.map((value: any, index: any) => (
            <div
              key={index}
              className="d-flex justify-content-between"
              style={{
                background: "#00409d",
                color: "#fff",
                borderRadius: "14px",
                padding: "3px 6px",
                fontWeight: "500",
              }}
            >
              {value}
              <span
                style={{ marginLeft: "3px" }}
                onClick={() => handleRemoveOtherEmails(index)}
              >
                <i
                  style={{ fontWeight: "bolder" }}
                  className="bi bi-x-circle"
                ></i>
              </span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default CustomSendEmail;
