import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { type Book, type InputBook } from './Book';

type Props = {
  onSave: (book: InputBook) => void;
  book?: Book;
};

const defaultValues: InputBook = {
  title: '',
  author: '',
  isbn: '',
};

const BookForm: React.FC<Props> = ({ onSave, book: inputBook }) => {
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<InputBook>({
    defaultValues,
  });

  useEffect(() => {
    if (inputBook) {
      reset(inputBook);
    }
  }, [inputBook, reset]);

  return (
    <form className="BookForm" onSubmit={handleSubmit(onSave)}>
      <div>
        <label htmlFor="title">Titel:</label>
        <input
          type="text"
          {...register('title', {
            required: true,
            minLength: 4,
            maxLength: 25,
          })}
        />
        {errors.title && errors.title.type === 'required' && (
          <div>Titel ist ein Pflichtfeld.</div>
        )}
        {errors.title && errors.title.type === 'minLength' && (
          <div>Der Titel muss mindestens 4 Zeichen lang sein.</div>
        )}
        {errors.title && errors.title.type === 'maxLength' && (
          <div>Der Titel darf höchstens 25 Zeichen lang sein.</div>
        )}
      </div>
      <div>
        <label htmlFor="author">Autor:</label>
        <input type="text" {...register('author', { required: true })} />
        {errors.author && <div>Autor ist ein Pflichtfeld</div>}
      </div>
      <div>
        <label htmlFor="isbn">ISBN:</label>
        <input type="text" {...register('isbn', { required: true })} />
        {errors.isbn && <div>ISBN ist ein Pflichtfeld</div>}
      </div>
      <div>
        <button type="submit">speichern</button>
      </div>
    </form>
  );
};

export default BookForm;
