'use client';

import { NextPage } from 'next';
import { saveBookAction } from '@/books/book.actions';
import { useActionState } from 'react';

const CreateBookPage: NextPage = () => {
  const [state, formAction, isPending] = useActionState(saveBookAction, {
    error: null,
    values: null,
  });

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

      <form action={formAction}>
        <div>
          <label>Titel</label>
          <input name="title" defaultValue={state.values?.title ?? ''} />
          {state.error && 'title' in state.error && (
            <p style={{ color: 'red' }}>
              {(state.error.title as string[]).join(', ')}
            </p>
          )}
        </div>

        <div>
          <label>Autor</label>
          <input name="author" defaultValue={state.values?.author ?? ''} />
          {state.error && 'author' in state.error && (
            <p style={{ color: 'red' }}>
              {(state.error.author as string[]).join(', ')}
            </p>
          )}
        </div>

        <div>
          <label>ISBN</label>
          <input name="isbn" defaultValue={state.values?.isbn ?? ''} />
          {state.error && 'isbn' in state.error && (
            <p style={{ color: 'red' }}>
              {(state.error.isbn as string[]).join(', ')}
            </p>
          )}
        </div>

        {state.error && 'api' in state.error && (
          <p style={{ color: 'red' }}>{state.error.api.join(', ')}</p>
        )}

        <button type="submit" disabled={isPending}>
          {isPending ? 'Speichern…' : 'Speichern'}
        </button>
      </form>
    </div>
  );
};

export default CreateBookPage;
