'use client';

import { saveBookAction } from '@/books/book.actions';
import { zodResolver } from '@hookform/resolvers/zod';
import { NextPage } from 'next';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod/v4';

const BookSchema = z.object({
  title: z.string().min(1, 'Titel ist erforderlich'),
  author: z.string().min(1, 'Autor ist erforderlich'),
  isbn: z.string().min(3, 'ISBN ist zu kurz'),
});

type Book = z.infer<typeof BookSchema>;

const CreateBookPage: NextPage = () => {
  const [error, setError] = useState('');
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Book>({
    resolver: zodResolver(BookSchema),
  });

  return (
    <div>
      <h1>Neues Buch</h1>

      <form
        onSubmit={handleSubmit(async (book) => {
          const error = await saveBookAction(book);
          if (error) {
            setError(error);
          }
        })}
      >
        {error && <p style={{ color: 'red' }}>{error}</p>}
        <div>
          <label>Titel</label>
          <input {...register('title')} />
          {errors.title && (
            <p style={{ color: 'red' }}>{errors.title.message}</p>
          )}
        </div>

        <div>
          <label>Autor</label>
          <input {...register('author')} />
          {errors.author && (
            <p style={{ color: 'red' }}>{errors.author.message}</p>
          )}
        </div>

        <div>
          <label>ISBN</label>
          <input {...register('isbn')} />
          {errors.isbn && <p style={{ color: 'red' }}>{errors.isbn.message}</p>}
        </div>

        <button type="submit">Speichern</button>
      </form>
    </div>
  );
};

export default CreateBookPage;
