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

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

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

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

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

  const fileRef = useRef<HTMLInputElement>(null);

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

  function handleSubmit(event: FormEvent<HTMLFormElement>): void {
    event.preventDefault();
    const formData = new FormData();
    formData.append('title', book.title);
    if (fileRef.current?.files && fileRef.current?.files[0]) {
      formData.append('image', fileRef.current?.files[0]);
    }
    onSave(formData);
    setBook(initialBook);
  }

  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="image">Bild:</label>
        <input type="file" id="image" ref={fileRef} />
      </div>
      <div>
        <button type="submit">speichern</button>
      </div>
    </form>
  );
};

export default BookForm;
