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

interface INameInput<T> {
  name: string;
  value: T;
  label?: string | null;
  placeholder?: string | null;
  inputClassName?: string;
  onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void;
  onValid: (value: string) => void;
  onInvalid: () => void;
}

const isValidName = (name: string) => {
  return name.length > 0 && name.length < 30;
};

function NameInput(props: INameInput<string>): JSX.Element {
  const { name, value, placeholder, onValid, onInvalid, onKeyDown } = props;
  const [userName, setUserName] = useState(value);
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setUserName(event.target.value);
  };

  useEffect(() => {
    if (isValidName(userName)) {
      onValid(userName);
    } else {
      onInvalid();
    }
  }, [userName, onInvalid, onValid]);

  return (
    <div className={styles["name-input-container"]}>
      <input
        name={name}
        type="text"
        value={userName}
        onChange={handleChange}
        onKeyDown={onKeyDown}
        placeholder={placeholder ?? " "}
      />
    </div>
  );
}

export default NameInput;
