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

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

const isValidPassword = (password: string) => {
  return !!(password.length >= 6 && password.length < 30);
};

function PasswordInput({
  inputClassName,
  value,
  placeholder,
  onValid,
  onInvalid,
}: IPasswordInputProps & Partial<FormField<string>>) {
  const [password, setPassword] = useState(value);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const password = event.target.value;
    if (!isValidPassword(password)) {
      onInvalid();
    } else {
      onValid(password);
    }
    setPassword(password);
  };

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

export default PasswordInput;
