import { useEffect, useState } from "react";
import { FormField } from "@/types";
import styles from "./styles.module.css";

const isValidEmail = (email: string) => {
  const re =
    /^(([^<>()[\]\\.,:\s@"]+(\.[^<>()[\]\\.,:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase().trim());
};

type EmailInputProps = FormField<string> & {
  className?: string;
  readonly?: boolean;
};

function EmailInput(props: EmailInputProps): JSX.Element {
  const { name, value, placeholder, onValid, onInvalid, className, readonly } = props;
  const [email, setEmail] = useState(value);

  const handleChangeEmail = (event: React.ChangeEvent<HTMLInputElement>) => {
    const email = event.target.value;
    if (!isValidEmail(email)) {
      onInvalid();
    } else {
      onValid(email);
    }
    setEmail(email);
  };

  useEffect(() => {
    if (isValidEmail(email)) {
      onValid(email);
    } else {
      onInvalid();
    }
  }, [email, onInvalid, onValid]);

  return (
    <div className={styles["input-container"]}>
      <input
        type="email"
        name={name}
        className={className}
        id="email"
        value={email}
        onChange={handleChangeEmail}
        placeholder=" "
        readOnly={readonly}
      />
      <span className={styles["input__placeholder"]}>{placeholder}</span>
    </div>
  );
}

export default EmailInput;
