import { useEffect, useState } from "react";
import { BookOpen, LibraryBig, ScanLine } from "lucide-react";
import { api } from "../api/client";
import type { DashboardData } from "../api/types";
import { bookDisplayTitle, bookVolumeLabel } from "../book/metadata";
import { EmptyState, LoadingState, Meter, Panel } from "../components/ui";
import { navigate } from "../router";

export function HomePage() {
  const [state, setState] = useState<DashboardData | null>(null);

  useEffect(() => {
    let alive = true;
    Promise.all([api.books(), api.continueReading(), api.libraries(), api.jobs()])
      .then(([books, continueReading, libraries, jobs]) => {
        if (!alive) return;
        setState({ books, continueReading, libraries, jobs });
      })
      .catch(() => {
        if (alive) setState({ books: [], continueReading: [], libraries: [], jobs: [] });
      });
    return () => {
      alive = false;
    };
  }, []);

  if (!state) return <LoadingState />;

  const renderHomeBook = (
    item: DashboardData["books"][number],
    className = "home-book-card",
    options: { href?: string; progressPercent?: number } = {}
  ) => {
    const volumeLabel = bookVolumeLabel(item);
    return (
      <button key={item.id} className={className} onClick={() => navigate(options.href ?? `/book/${item.id}`)}>
        <span className="home-book-cover" aria-hidden="true">
          {item.coverPath ? <img src={api.bookCoverUrl(item.id)} alt="" /> : <BookOpen size={24} />}
        </span>
        <span className="home-book-copy">
          {volumeLabel && <span className="home-book-volume">{volumeLabel}</span>}
          <strong>{bookDisplayTitle(item)}</strong>
          <span>{item.author ?? "Auteur inconnu"}</span>
          {options.progressPercent !== undefined && <Meter value={options.progressPercent} />}
        </span>
      </button>
    );
  };

  return (
    <div className="page-grid home-page">
      <section className="hero-band home-hero">
        <div>
          <h1>Reprendre la lecture.</h1>
        </div>
        <button className="primary-button" onClick={() => navigate("/search")}>
          <ScanLine size={18} />
          Explorer
        </button>
      </section>

      <Panel className="span-2">
        <div className="section-heading">
          <h2>Livres en cours</h2>
          <span>{state.continueReading.length} lectures</span>
        </div>
        {state.continueReading.length ? (
          <div className="continue-grid">
            {state.continueReading.map((item) =>
              renderHomeBook(item.book, "home-book-card continue-tile", {
                href: `/reader/${item.book.id}`,
                progressPercent: item.progress.percent
              })
            )}
          </div>
        ) : (
          <EmptyState title="Aucune trace" detail="Les lectures reprises apparaitront ici." />
        )}
      </Panel>

      <Panel>
        <div className="section-heading">
          <h2>Bibliotheques</h2>
          <LibraryBig size={20} />
        </div>
        <div className="library-list">
          {state.libraries.map((library) => (
            <button key={library.id} onClick={() => navigate(`/library/${library.id}`)}>
              <strong>{library.name}</strong>
              <span>{library.path}</span>
            </button>
          ))}
        </div>
      </Panel>

      <section className="home-book-grid span-3">
        {state.books.map((book) => renderHomeBook(book))}
      </section>
    </div>
  );
}
