import React from 'react';

export const useTextInput = ({
  initialValue,
  maxLength,
  onChange,
}: {
  initialValue: string;
  maxLength?: number;
  onChange: (value: string) => void;
}) => {
  const [value, setValue] = React.useState(initialValue || '');
  const charCount = maxLength ? maxLength - value.length : undefined;

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    const newValue = e.target.value;

    if (
      maxLength === undefined ||
      (maxLength && newValue.length <= maxLength)
    ) {
      setValue(newValue);
      onChange?.(newValue);
    }
  };

  return {
    value,
    charCount,
    handleChange,
  };
};
