import { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faChevronLeft, faTrash } from '@fortawesome/free-solid-svg-icons';
import ImageGlow from 'react-image-glow';
import BookCard from '../components/BookCard.jsx';
import { useSavedBooks } from '../context/SavedBooksContext.jsx';

export default function MyBooksPage() {
  const { savedBooks, removeBook } = useSavedBooks();
  const [selected, setSelected] = useState(null);

  const handleRemove = (title) => {
    removeBook(title);
    setSelected(null);
  };

  if (selected) {
    return (
      <section className="mybooks-detail">
        <button type="button" className="back-btn" onClick={() => setSelected(null)}>
          <FontAwesomeIcon icon={faChevronLeft} /> Back
        </button>

        <div className="detail-hero">
          {selected.thumbImage ? (
            <div className="detail-hero-glow">
              <ImageGlow radius={60} saturation={1.4} opacity={0.9}>
                <img src={selected.thumbImage} alt={selected.title} className="detail-hero-img" />
              </ImageGlow>
            </div>
          ) : (
            <div className="placeholder-thumb">NO COVER</div>
          )}
        </div>

        <div className="detail-body">
          <h1>{selected.title}</h1>
          <p className="book-meta">{selected.authorName || 'Unknown author'}</p>
          <p className="book-meta">
            {selected.page ? `${selected.page} pages` : 'Page count N/A'} · {selected.rate || '-'} ★
          </p>
          <p className="book-meta">{selected.publisher || 'Publisher unknown'}</p>
          <p className="book-description">{selected.description || 'Description not available.'}</p>
          <button type="button" className="secondary-btn" onClick={() => handleRemove(selected.title)}>
            <FontAwesomeIcon icon={faTrash} /> Remove from My Books
          </button>
        </div>
      </section>
    );
  }

  return (
    <section className="mybooks-list">
      {savedBooks.length === 0 && <p className="status-text info">Henüz kayitli kitap yok.</p>}
      {savedBooks.map((book, index) => (
        <BookCard key={`${book.title}-${index}`} book={book} onSelect={setSelected} />
      ))}
    </section>
  );
}
