import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod/v4';

const bookSchema = z.object({
  title: z.string().min(1, 'Titel ist erforderlich.'),
});

type Book = z.infer<typeof bookSchema>;

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

const BookForm: React.FC<Props> = ({ onSave }) => {
  const {
    handleSubmit,
    register,
    formState: { errors },
  } = useForm<Book>({
    resolver: zodResolver(bookSchema),
  });

  return (
    <form onSubmit={handleSubmit((data) => onSave(data))}>
      <label>
        Titel:
        <input type="text" {...register('title')} data-testid="title-input" />
      </label>
      {errors.title && (
        <div data-testid="title-error">{errors.title.message}</div>
      )}
      <button type="submit" data-testid="submit">
        speichern
      </button>
    </form>
  );
};

export default BookForm;
