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

interface INameInputProps {
  value: string;
  placeholder: string;
  placeholderClassName?: string;
  inputContainerClassName?: string;
  readonly?: boolean;
  onValid: (value: string) => void;
  onInvalid: () => void;
}

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

function NameInput({
  inputClassName,
  inputContainerClassName = "",
  value,
  placeholder,
  placeholderClassName,
  onValid,
  onInvalid,
  readonly = false,
}: INameInputProps & Partial<FormField<string>>) {
  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"]} ${inputContainerClassName}`}>
      <input
        className={inputClassName}
        type="text"
        name="name"
        id="name"
        value={name}
        onChange={handleChangeName}
        placeholder=" "
        autoComplete="name"
        readOnly={readonly}
      />
      <span className={`${styles["input__placeholder"]} ${placeholderClassName}`}>{placeholder}</span>
    </div>
  );
}

export default NameInput;
