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

interface INameInputProps {
  value: string;
  placeholder: string;
  onValid: (value: string) => void;
  onInvalid: () => void;
}

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

function NameInput({
  value,
  placeholder,
  onValid,
  onInvalid,
}: INameInputProps) {
  const [name, setName] = useState(value);

  const handleChangeName = (event: React.ChangeEvent<HTMLInputElement>) => {
    const name = event.target.value;
    if (!isValidName(name)) {
      onInvalid();
    } else {
      onValid(name);
    }
    setName(name);
  };

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

export default NameInput;
