import React, { useState } from "react";
import { useAnnotations } from "@/context/AnnotationsContext";
import type { Bookmark } from "@/types";

interface BookmarkListProps {
  bookId?: string;
  onNavigateToPage?: (bookId: string, page: number) => void;
}

export function BookmarkList({
  bookId,
  onNavigateToPage,
}: BookmarkListProps): React.ReactElement {
  const { state, loadBookmarks, removeBookmark } = useAnnotations();
  const [deletingId, setDeletingId] = useState<string | null>(null);

  React.useEffect(() => {
    loadBookmarks(bookId);
  }, [loadBookmarks, bookId]);

  const handleDelete = async (id: string): Promise<void> => {
    setDeletingId(id);
    try {
      await removeBookmark(id);
    } catch {
      // error handled by context
    } finally {
      setDeletingId(null);
    }
  };

  if (state.bookmarksLoading) {
    return <div className="annotations-loading">Loading bookmarks...</div>;
  }

  if (state.bookmarks.length === 0) {
    return (
      <div className="annotations-empty">
        No bookmarks yet. Select a passage and add a bookmark while reading.
      </div>
    );
  }

  return (
    <div className="annotations-list">
      {state.bookmarks.map((bookmark: Bookmark) => (
        <div key={bookmark.id} className="annotation-card">
          <div className="annotation-card-header">
            <span className="annotation-kind-badge bookmark-badge">
              Bookmark
            </span>
            <span className="annotation-page">
              Page {bookmark.page}
            </span>
            <span className="annotation-date">
              {new Date(bookmark.created_at).toLocaleDateString()}
            </span>
          </div>
          {bookmark.location_text && (
            <blockquote className="annotation-quote">
              &ldquo;{bookmark.location_text}&rdquo;
            </blockquote>
          )}
          <div className="annotation-actions">
            {onNavigateToPage && (
              <button
                className="btn btn-sm"
                onClick={() =>
                  onNavigateToPage(bookmark.book, bookmark.page)
                }
              >
                Go to page
              </button>
            )}
            <button
              className="btn btn-sm btn-danger"
              onClick={() => handleDelete(bookmark.id)}
              disabled={deletingId === bookmark.id}
            >
              {deletingId === bookmark.id ? "Deleting..." : "Delete"}
            </button>
          </div>
        </div>
      ))}
    </div>
  );
}