'use client';

import { FormEvent, useState, useEffect } from 'react';
import Link from 'next/link';
import { Album } from '@/entities/album.entity';
import { createAlbum } from '@/app/actions';
import { useRouter } from 'next/navigation';

export default function Page() {
  const [albums, setAlbums] = useState<Album[]>([]);
  const router = useRouter();

  useEffect(() => {
    async function fetchAlbums() {
      const response = await fetch('https://api.anatid.net/album');
      const data = await response.json();
      setAlbums(data);
    }
    fetchAlbums();
  }, []);

  if (!albums) return <div>Loading...</div>

  async function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();

    const formData = new FormData(event.currentTarget);
    const response = await createAlbum(formData);

    await response.json();
    router.refresh();
  }

  return (
    <div className="container">
      <ul>
        {albums.map((album: Album) => (
          <li key={album.id}>
            <Link
              href={{
                pathname: `/album/${album.id}`
              }}
            >{album.title}
            </Link> by {album.artist} ({album.genre})</li>
        ))}
      </ul>
      <form onSubmit={onSubmit}>
        <span>Album Title</span><input type="text" name="title" /><br/>
        <span>Artist</span><input type="text" name="artist" /><br/>
        <span>Genre</span><input type="text" name="genre" /><br/>
        <button type="submit">Create</button>
      </form>
    </div>
  );
}
