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());
};

interface IEmailInputProps {
  inputContainerClassName?: string;
  placeholderClassName?: string;
  readonly?: boolean;
}

function EmailInput(props: FormField<string> & IEmailInputProps): JSX.Element {
  const {
    name,
    value,
    placeholder,
    inputClassName,
    inputContainerClassName = "",
    placeholderClassName = "",
    onValid,
    onInvalid,
    readonly = false,
  } = 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"]} ${inputContainerClassName}`}>
      <input
        className={inputClassName}
        type="email"
        name={name}
        id="email"
        value={email}
        onChange={handleChangeEmail}
        placeholder=" "
        autoComplete="email"
        readOnly={readonly}
      />
      <span
        className={`${styles["input__placeholder"]} ${placeholderClassName}`}
      >
        {placeholder}
      </span>
    </div>
  );
}

export default EmailInput;
