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

interface IBirthplaceInputProps {
  value: string;
  placeholder: string;
  placeholderClassName?: string;
  onValid: (value: string) => void;
  onInvalid: () => void;
}

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

function BirthplaceInput({
  inputClassName,
  value = "",
  placeholder,
  placeholderClassName,
  onValid,
  onInvalid,
}: IBirthplaceInputProps & Partial<FormField<string>>) {
  const [birthplace, setBirthplace] = useState(value);

  const handleChangeBirthplace = (event: React.ChangeEvent<HTMLInputElement>) => {
    const birthplace = event.target.value;
    if (!isValidBirthplace(birthplace)) {
      onInvalid();
    } else {
      onValid(birthplace);
    }
    setBirthplace(birthplace);
  };

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

export default BirthplaceInput;
