import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { type Book, type InputBook, inputBookSchema } from './Book';
import { zodResolver } from '@hookform/resolvers/zod';

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,
    resolver: zodResolver(inputBookSchema),
  });

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

export default BookForm;
