import React, {
  type ChangeEvent,
  type FormEvent,
  useEffect,
  useState,
} from 'react';
import { type Book, type InputBook } from './Book';

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

const initialBook: InputBook = {
  title: '',
  author: '',
  isbn: '',
};

const BookForm: React.FC<Props> = ({ onSave, book: inputBook }) => {
  const [book, setBook] = useState<InputBook>(initialBook);

  useEffect(() => {
    if (inputBook) {
      setBook(inputBook);
    }
  }, [inputBook]);

  function handleChange(event: ChangeEvent<HTMLInputElement>): void {
    setBook((prevBook) => {
      return { ...prevBook, [event.target.name]: event.target.value };
    });
  }

  function handleSubmit(event: FormEvent<HTMLFormElement>): void {
    event.preventDefault();
    onSave(book);
  }

  return (
    <form className="BookForm" onSubmit={handleSubmit}>
      <div>
        <label htmlFor="title">Titel:</label>
        <input
          type="text"
          id="title"
          name="title"
          value={book.title}
          onChange={handleChange}
        />
      </div>
      <div>
        <label htmlFor="author">Autor:</label>
        <input
          type="text"
          id="author"
          name="author"
          value={book.author}
          onChange={handleChange}
        />
      </div>
      <div>
        <label htmlFor="isbn">ISBN:</label>
        <input
          type="text"
          id="isbn"
          name="isbn"
          value={book.isbn}
          onChange={handleChange}
        />
      </div>
      <div>
        <button type="submit">speichern</button>
      </div>
    </form>
  );
};

export default BookForm;
