import React, { useCallback, useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { booksApi } from "../api/books";
import type { BookListItem, BookSearchParams } from "../types/book";
import { READING_STATUS_OPTIONS } from "../types/book";
import { useAuth } from "../context/AuthContext";

interface FilterState {
  genre: string;
  author: string;
  reading_status: string;
}

function useDebounce<T>(value: T, delay: number): T {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const timer = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);
  return debounced;
}

export function LibraryPage() {
  const navigate = useNavigate();
  const { logout } = useAuth();

  const [books, setBooks] = useState<BookListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [filters, setFilters] = useState<FilterState>({ genre: "", author: "", reading_status: "" });
  const [genres, setGenres] = useState<string[]>([]);
  const [authors, setAuthors] = useState<string[]>([]);
  const [totalCount, setTotalCount] = useState(0);
  const [showFilters, setShowFilters] = useState(false);

  const debouncedSearch = useDebounce(searchQuery, 300);
  const loadedRef = useRef(false);

  // Load filter options once
  useEffect(() => {
    if (loadedRef.current) return;
    loadedRef.current = true;
    void Promise.all([booksApi.getGenres(), booksApi.getAuthors()]).then(
      ([genreList, authorList]) => {
        setGenres(genreList);
        setAuthors(authorList);
      },
      () => {
        // Filters degrade gracefully if discovery endpoints fail
      },
    );
  }, []);

  const loadBooks = useCallback(async (params: BookSearchParams) => {
    setLoading(true);
    setError(null);
    try {
      const response = await booksApi.searchBooks(params);
      setBooks(response.results);
      setTotalCount(response.count);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load books");
      setBooks([]);
      setTotalCount(0);
    } finally {
      setLoading(false);
    }
  }, []);

  // Reload when search or filters change
  useEffect(() => {
    const params: BookSearchParams = {};
    if (debouncedSearch) params.q = debouncedSearch;
    if (filters.genre) params.genre = filters.genre;
    if (filters.author) params.author = filters.author;
    if (filters.reading_status) params.reading_status = filters.reading_status;
    void loadBooks(params);
  }, [debouncedSearch, filters, loadBooks]);

  const handleFilterChange = (key: keyof FilterState, value: string) => {
    setFilters((prev) => ({ ...prev, [key]: value }));
  };

  const clearAllFilters = () => {
    setSearchQuery("");
    setFilters({ genre: "", author: "", reading_status: "" });
  };

  const hasActiveFilters = !!searchQuery || !!filters.genre || !!filters.author || !!filters.reading_status;

  return (
    <div style={{ maxWidth: 960, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
      {/* Header */}
      <header style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        marginBottom: 20, padding: "16px 0", borderBottom: "1px solid #e5e7eb", flexWrap: "wrap", gap: 8,
      }}>
        <div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: "#1f2937", margin: 0 }}>Library</h1>
          {!loading && <p style={{ fontSize: 13, color: "#6b7280", marginTop: 2 }}>{totalCount} book{totalCount !== 1 ? "s" : ""}</p>}
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <button onClick={() => navigate("/add")} className="btn">+ Add Book</button>
          <button onClick={() => navigate("/bookmarks-notes")} className="btn btn-secondary">Bookmarks</button>
          <button onClick={() => navigate("/settings")} className="btn btn-secondary">Settings</button>
          <button onClick={logout} className="btn btn-danger">Logout</button>
        </div>
      </header>

      {/* Search Bar */}
      <div style={{ marginBottom: 16 }}>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <div style={{ flex: 1, position: "relative" }}>
            <input
              type="text"
              placeholder="Search by title, author, or genre..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              style={{
                width: "100%", padding: "12px 16px 12px 44px", borderRadius: 10,
                border: "1px solid #e5e7eb", fontSize: 15, background: "#fff",
                outline: "none", boxSizing: "border-box",
              }}
            />
            <span style={{
              position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)",
              fontSize: 18, color: "#9ca3af", pointerEvents: "none",
            }}>🔍</span>
          </div>
          <button
            onClick={() => setShowFilters(!showFilters)}
            className={`btn ${showFilters ? "" : "btn-secondary"}`}
            title="Toggle filters"
          >
            {showFilters ? "▲ Filters" : "▼ Filters"}
          </button>
        </div>
      </div>

      {/* Filters Panel */}
      {showFilters && (
        <div style={{
          background: "#fff", borderRadius: 10, padding: 16, marginBottom: 16,
          border: "1px solid #e5e7eb", display: "flex", gap: 12, flexWrap: "wrap", alignItems: "end",
        }}>
          <div style={{ minWidth: 160, flex: 1 }}>
            <label style={{ display: "block", fontSize: 12, fontWeight: 600, color: "#6b7280", marginBottom: 4 }}>Genre</label>
            <select
              value={filters.genre}
              onChange={(e) => handleFilterChange("genre", e.target.value)}
              style={{
                width: "100%", padding: "8px 12px", borderRadius: 6, border: "1px solid #e5e7eb",
                fontSize: 14, background: "#fff", cursor: "pointer",
              }}
            >
              <option value="">All Genres</option>
              {genres.map((g) => <option key={g} value={g}>{g}</option>)}
            </select>
          </div>
          <div style={{ minWidth: 160, flex: 1 }}>
            <label style={{ display: "block", fontSize: 12, fontWeight: 600, color: "#6b7280", marginBottom: 4 }}>Author</label>
            <select
              value={filters.author}
              onChange={(e) => handleFilterChange("author", e.target.value)}
              style={{
                width: "100%", padding: "8px 12px", borderRadius: 6, border: "1px solid #e5e7eb",
                fontSize: 14, background: "#fff", cursor: "pointer",
              }}
            >
              <option value="">All Authors</option>
              {authors.map((a) => <option key={a} value={a}>{a}</option>)}
            </select>
          </div>
          <div style={{ minWidth: 160, flex: 1 }}>
            <label style={{ display: "block", fontSize: 12, fontWeight: 600, color: "#6b7280", marginBottom: 4 }}>Status</label>
            <select
              value={filters.reading_status}
              onChange={(e) => handleFilterChange("reading_status", e.target.value)}
              style={{
                width: "100%", padding: "8px 12px", borderRadius: 6, border: "1px solid #e5e7eb",
                fontSize: 14, background: "#fff", cursor: "pointer",
              }}
            >
              {READING_STATUS_OPTIONS.map((opt) => <option key={opt.value} value={opt.value}>{opt.label}</option>)}
            </select>
          </div>
          {hasActiveFilters && (
            <button onClick={clearAllFilters} className="btn btn-secondary" style={{ whiteSpace: "nowrap" }}>
              ✕ Clear
            </button>
          )}
        </div>
      )}

      {/* Error State */}
      {error && (
        <div style={{ background: "#fef2f2", padding: 16, borderRadius: 8, marginBottom: 16, textAlign: "center" }}>
          <p style={{ color: "#dc2626", fontSize: 14 }}>{error}</p>
          <button onClick={() => void loadBooks({})} style={{ marginTop: 8, padding: "8px 16px", border: "none", borderRadius: 6, background: "#dc2626", color: "#fff", cursor: "pointer", fontSize: 13 }}>Retry</button>
        </div>
      )}

      {/* Loading State */}
      {loading && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 16, opacity: 0.6 }}>
          {Array.from({ length: 8 }).map((_, i) => (
            <div key={i} style={{ background: "#fff", borderRadius: 12, overflow: "hidden", boxShadow: "0 2px 8px rgba(0,0,0,0.06)" }}>
              <div style={{ height: 180, background: "#f0f0f0" }} />
              <div style={{ padding: 12 }}>
                <div style={{ height: 14, background: "#f0f0f0", borderRadius: 4, marginBottom: 6, width: "70%" }} />
                <div style={{ height: 12, background: "#f0f0f0", borderRadius: 4, width: "40%" }} />
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Empty State */}
      {!loading && !error && books.length === 0 && (
        <div style={{ textAlign: "center", padding: "80px 20px" }}>
          <div style={{ fontSize: 64, marginBottom: 16 }}>{hasActiveFilters ? "🔍" : "📚"}</div>
          <h2 style={{ fontSize: 20, color: "#1f2937", marginBottom: 8 }}>
            {hasActiveFilters ? "No books found" : "Your library is empty"}
          </h2>
          <p style={{ color: "#6b7280", marginBottom: 20, fontSize: 15, lineHeight: 1.5 }}>
            {hasActiveFilters
              ? "Try adjusting your search query or filters to discover more books."
              : "Add a book to get started building your collection."}
          </p>
          {hasActiveFilters ? (
            <button onClick={clearAllFilters} className="btn" style={{ padding: "10px 24px" }}>
              Clear All Filters
            </button>
          ) : (
            <button onClick={() => navigate("/add")} className="btn" style={{ padding: "10px 24px" }}>
              Add Your First Book
            </button>
          )}
        </div>
      )}

      {/* Results Grid */}
      {!loading && books.length > 0 && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 16 }}>
          {books.map((book) => {
            const statusColors: Record<string, { bg: string; text: string }> = {
              want_to_read: { bg: "#dbeafe", text: "#1d4ed8" },
              reading: { bg: "#dcfce7", text: "#16a34a" },
              finished: { bg: "#f3e8ff", text: "#9333ea" },
              dnf: { bg: "#fef3c7", text: "#b45309" },
            };
            const sc = statusColors[book.reading_status] ?? { bg: "#f3f4f6", text: "#6b7280" };

            return (
              <div
                key={book.id}
                onClick={() => navigate(`/books/${book.id}`)}
                style={{
                  background: "#fff", borderRadius: 12, overflow: "hidden",
                  boxShadow: "0 2px 8px rgba(0,0,0,0.06)", cursor: "pointer",
                  transition: "transform 0.15s, box-shadow 0.15s",
                }}
                onMouseEnter={(e) => {
                  (e.currentTarget as HTMLElement).style.transform = "translateY(-2px)";
                  (e.currentTarget as HTMLElement).style.boxShadow = "0 4px 16px rgba(0,0,0,0.1)";
                }}
                onMouseLeave={(e) => {
                  (e.currentTarget as HTMLElement).style.transform = "";
                  (e.currentTarget as HTMLElement).style.boxShadow = "0 2px 8px rgba(0,0,0,0.06)";
                }}
              >
                <div style={{ height: 180, background: "#f0f0f0", display: "flex", alignItems: "center", justifyContent: "center", position: "relative" }}>
                  {book.cover_image
                    ? <img src={book.cover_image} alt={book.title} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                    : <span style={{ fontSize: 48 }}>📖</span>}
                  <span style={{
                    position: "absolute", top: 8, right: 8,
                    background: sc.bg, color: sc.text, fontSize: 11, fontWeight: 600,
                    padding: "2px 8px", borderRadius: 999, lineHeight: "18px",
                  }}>
                    {book.reading_status_display}
                  </span>
                </div>
                <div style={{ padding: 12 }}>
                  <h3 style={{ fontSize: 14, fontWeight: 600, color: "#1f2937", marginBottom: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {book.title}
                  </h3>
                  <p style={{ fontSize: 12, color: "#6b7280", marginBottom: 4 }}>
                    {book.author || "Unknown Author"}
                  </p>
                  {book.genre && (
                    <span style={{ fontSize: 11, color: "#4f46e5", background: "#eef2ff", padding: "1px 6px", borderRadius: 4 }}>
                      {book.genre}
                    </span>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}