/**
 * ReadingPage — routes to EPUB or PDF reading views by ebook format.
 */

import { useEffect, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18n-lite";
import { booksApi } from "../api/books";
import { EpubReadingView } from "../components/reader/EpubReadingView";
import { PdfReadingView } from "../components/reader/PdfReadingView";
import type { EBookDetail } from "../types/book";
import "../reader.css";

type LocationState = { epubLocation?: string } | null;

export default function ReadingPage() {
  const { t } = useTranslation();
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const routerLocation = useLocation();
  const bookId = Number(id);
  const initialAnchor = (routerLocation.state as LocationState)?.epubLocation;

  const [book, setBook] = useState<EBookDetail | null>(null);
  const [bookLoading, setBookLoading] = useState(true);
  const [bookError, setBookError] = useState<string | null>(null);

  useEffect(() => {
    if (!bookId || Number.isNaN(bookId)) return;
    setBookLoading(true);
    setBookError(null);
    booksApi
      .getEBook(bookId)
      .then((data) => setBook(data))
      .catch(() => setBookError(t("reader.loadBookFailed")))
      .finally(() => setBookLoading(false));
  }, [bookId, t]);

  if (bookLoading) {
    return (
      <div className="reader-loading">
        <div className="spinner" />
        <p>{t("reader.loading")}</p>
      </div>
    );
  }

  if (bookError || !book) {
    return (
      <div className="reader-loading">
        <p className="reader-error">{bookError ?? t("reader.unableToOpen")}</p>
        <button type="button" className="back-button" onClick={() => navigate("/")}>
          {t("reader.backToLibrary")}
        </button>
      </div>
    );
  }

  if (book.format === "pdf") {
    return <PdfReadingView book={book} bookId={bookId} initialAnchor={initialAnchor} />;
  }

  if (book.format !== "epub") {
    return (
      <div className="reader-loading">
        <p className="reader-error">{t("reader.unsupportedFormat")}</p>
        <button type="button" className="back-button" onClick={() => navigate("/")}>
          {t("reader.backToLibrary")}
        </button>
      </div>
    );
  }

  return (
    <EpubReadingView book={book} bookId={bookId} initialEpubLocation={initialAnchor} />
  );
}
