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 } = 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')} />
      </div>
      <div>
        <label htmlFor="author">Autor:</label>
        <input type="text" {...register('author')} />
      </div>
      <div>
        <label htmlFor="isbn">ISBN:</label>
        <input type="text" {...register('isbn')} />
      </div>
      <div>
        <button type="submit">speichern</button>
      </div>
    </form>
  );
};

export default BookForm;
