'use client';

import { FormEvent, MouseEvent, useState, useEffect } from 'react';
import Link from 'next/link';
import { Album } from '@/entities/album.entity';
import { createAlbum, getAlbum } from '@/app/actions';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
import { IconButton } from '@mui/material';
import { Delete, Edit } from '@mui/icons-material';

export default function Page() {
  const [albums, setAlbums] = useState<Album[]>([]);
  const [show, setShow] = useState(false);
  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);
  const [formAlbumTitle, setFormAlbumTitle] = useState("");
  const [formAlbumArtist, setFormAlbumArtist] = useState("");
  const [formAlbumGenre, setFormAlbumGenre] = useState("");

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

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    handleClose();

    const formData = new FormData(event.currentTarget);
    try {
      const response = await createAlbum(formData);
      const data = response.json();
      console.log(data);
    } catch (error) {
      console.error('Error creating Album:', error);
    }
  }

  const handleCreate = async () => {
    setFormAlbumTitle("");
    setFormAlbumArtist("");
    setFormAlbumGenre("");
    handleShow();
  }

  const handleEdit = async (event: MouseEvent<HTMLElement>) => {
    const id = event.currentTarget.getAttribute('id');
    if (id) {
      const response = await getAlbum(id);
      const data = await response.json();
      setFormAlbumTitle(data.title);
      setFormAlbumArtist(data.artist);
      setFormAlbumGenre(data.genre);
      handleShow();
    } else {
      console.error("Couldn't get ID of clicked element");
    }
  }

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

  return (
    <>
    <div className="container">
      <Button variant="primary" onClick={handleCreate}>
        Add Album
      </Button>
      <table className="u-full-width">
        <thead>
          <tr>
            <th>Title</th>
            <th>Artist</th>
            <th>Genre</th>
            <th>Controls</th>
          </tr>
        </thead>
        <tbody>
        {albums.map((album: Album) => (
          <tr key={album.id}>
            <td>
              <Link
                href={{
                  pathname: `/album/${album.id}`
                }}>{album.title}
              </Link>
            </td>
            <td>
              {album.artist}
            </td>
            <td>
              {album.genre}
            </td>
            <td>
              <IconButton aria-label="edit" size="small" id={album.id.toString()} onClick={handleEdit}>
                <Edit fontSize="inherit" />
              </IconButton>
              <IconButton aria-label="delete" size="small" id={album.id.toString()} onClick={handleEdit}>
                <Delete fontSize="inherit" />
              </IconButton>
            </td>
          </tr>
        ))}
        </tbody>
      </table>

    </div>

    <Modal
      show={show}
      onHide={handleClose}
      backdrop="static"
      keyboard={false}
    >
      <Modal.Header closeButton>
        <Modal.Title>Create Album</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <div>
          <form onSubmit={handleSubmit}>
            <div className="row">
              <div className="six columns">
                <label htmlFor="album-title">Album Title</label><input type="text" name="title" id="album-title" defaultValue={formAlbumTitle} />
              </div>
              <div className="six columns">
                <label htmlFor="album-artist">Artist</label><input type="text" name="artist" id="album-artist" defaultValue={formAlbumArtist} />
              </div>
            </div>
            <div className="row">
              <div className="six columns">
                <label htmlFor="album-genre">Genre</label><input type="text" name="genre" id="album-genre" defaultValue={formAlbumGenre} />
              </div>
            </div>
            <Button variant="primary" type="submit">Create</Button>
          </form>
        </div>
      </Modal.Body>
      <Modal.Footer>
        <Button variant="secondary" onClick={handleClose}>
          Close
        </Button>
      </Modal.Footer>
    </Modal>
    </>
  );
}
