import type { ReaderMetadata } from "../../types/reader";
import type { CurrentReader } from "./reader-context";
import { getState, setState } from "./reader-state";
import { readerEvents } from "./reader-events";
import { updateReadingProgress } from "./reader-services";

export function createNavigationAPI() {
  return {
    nextPage: () => {
      const state = getState();
      if (!state.currentReader) return;

      readerEvents.emit("beforePageChange", state.currentReader);

      if (state.currentReader.type === "ebook") {
        if (
          state.currentReader.currentSpineIndex <
          state.currentReader.cif.spine.length - 1
        ) {
          state.currentReader.currentSpineIndex++;
          renderSpineItem();
        }
      } else if (state.currentReader.type === "pdf") {
        const totalPages = state.readerMetadata?.total_pages || 0;
        if (state.currentReader.currentPage < totalPages) {
          state.currentReader.currentPage++;
          renderPDFPage();
        }
      } else if (
        state.currentReader.type === "comic" ||
        state.currentReader.type === "manga"
      ) {
        if (
          state.currentReader.currentPage <
          state.currentReader.images.length - 1
        ) {
          state.currentReader.currentPage++;
          renderComicPage();
        }
      }

      setState({ currentReader: state.currentReader });
      sendProgressUpdate();
      readerEvents.emit("pageChanged", getCurrentPage());
      readerEvents.emit("afterPageChange", state.currentReader);
    },

    previousPage: () => {
      const state = getState();
      if (!state.currentReader) return;

      readerEvents.emit("beforePageChange", state.currentReader);

      if (state.currentReader.type === "ebook") {
        if (state.currentReader.currentSpineIndex > 0) {
          state.currentReader.currentSpineIndex--;
          renderSpineItem();
        }
      } else if (state.currentReader.type === "pdf") {
        if (state.currentReader.currentPage > 1) {
          state.currentReader.currentPage--;
          renderPDFPage();
        }
      } else if (
        state.currentReader.type === "comic" ||
        state.currentReader.type === "manga"
      ) {
        if (state.currentReader.currentPage > 0) {
          state.currentReader.currentPage--;
          renderComicPage();
        }
      }

      setState({ currentReader: state.currentReader });
      sendProgressUpdate();
      readerEvents.emit("pageChanged", getCurrentPage());
      readerEvents.emit("afterPageChange", state.currentReader);
    },

    goToPage: (page: number) => {
      const state = getState();
      if (!state.currentReader) return;

      readerEvents.emit("beforePageChange", state.currentReader);

      if (state.currentReader.type === "ebook") {
        if (page >= 0 && page < state.currentReader.cif.spine.length) {
          state.currentReader.currentSpineIndex = page;
          renderSpineItem();
        }
      } else if (state.currentReader.type === "pdf") {
        if (page >= 1 && page <= (state.readerMetadata?.total_pages || 0)) {
          state.currentReader.currentPage = page;
          renderPDFPage();
        }
      } else if (
        state.currentReader.type === "comic" ||
        state.currentReader.type === "manga"
      ) {
        if (page >= 0 && page < state.currentReader.images.length) {
          state.currentReader.currentPage = page;
          renderComicPage();
        }
      }

      setState({ currentReader: state.currentReader });
      sendProgressUpdate();
      readerEvents.emit("pageChanged", page);
      readerEvents.emit("afterPageChange", state.currentReader);
    },

    goToChapter: (chapterIndex: number) => {
      const state = getState();
      if (!state.readerMetadata?.chapter_metadata?.chapters) return;

      const chapters = state.readerMetadata.chapter_metadata.chapters;
      if (chapterIndex < 0 || chapterIndex >= chapters.length) return;

      const chapter = chapters[chapterIndex];
      const pageAPI = createNavigationAPI();
      pageAPI.goToPage(chapter.start_page);

      readerEvents.emit("chapterChanged", chapter);
    },
  };
}

function renderSpineItem() {
  const state = getState();
  if (state.currentReader?.type !== "ebook") return;

  const spineItem =
    state.currentReader.cif.spine[state.currentReader.currentSpineIndex];
  const container = document.getElementById("reader-content");
  if (!container) return;

  container.innerHTML = spineItem.content;
  applyReaderTheme();
  applyTypography();
}

async function renderPDFPage() {
  const state = getState();
  if (state.currentReader?.type !== "pdf") return;

  const container = document.getElementById("reader-content");
  if (!container) return;

  const { getPDFPage } = await import("../pdf/pdfjs-wrapper");

  try {
    const page = await getPDFPage(state.currentReader.currentPage);
    const viewport = page.getViewport({ scale: 1.5 });
    const canvas = document.createElement("canvas");
    canvas.width = viewport.width;
    canvas.height = viewport.height;
    canvas.className = "pdf-page mx-auto";
    const ctx = canvas.getContext("2d");
    if (ctx) {
      await page.render({
        canvasContext: ctx,
        viewport: viewport,
        canvas: canvas,
      }).promise;
      container.innerHTML = "";
      container.appendChild(canvas);
    }
  } catch (error) {
    console.error("Failed to render PDF page:", error);
  }
}

function renderComicPage() {
  const state = getState();
  if (
    state.currentReader?.type !== "comic" &&
    state.currentReader?.type !== "manga"
  )
    return;

  const container = document.getElementById("reader-content");
  if (
    !container ||
    !state.currentReader.images[state.currentReader.currentPage]
  )
    return;

  const img = document.createElement("img");
  img.src = URL.createObjectURL(
    state.currentReader.images[state.currentReader.currentPage],
  );
  img.className = "w-full h-contain object-contain";
  img.alt = `Page ${state.currentReader.currentPage + 1}`;
  container.innerHTML = "";
  container.appendChild(img);
}

function applyReaderTheme() {
  const state = getState();
  const settings = getReaderSettings();
  const container = document.getElementById("reader-content");
  if (!container) return;

  container.className = `ebook-content theme-${settings.reading_theme}`;
}

function applyTypography() {
  const state = getState();
  const settings = getReaderSettings();
  const container = document.getElementById("reader-content");
  if (!container) return;

  container.style.fontSize = `${settings.font_size}px`;
  container.style.lineHeight = settings.line_height.toString();
  container.style.fontFamily = getFontStack(settings.reading_font);
}

function getFontStack(font: string): string {
  const stacks: Record<string, string> = {
    literata: '"Literata", serif',
    crimson: '"Crimson Text", serif',
    "source-serif": '"Source Serif 4", serif',
    "eb-garamond": '"EB Garamond", serif',
    libertinus: '"Libertinus Serif", serif',
    "noto-serif": '"Noto Serif", serif',
    "charis-sil": '"Charis SIL", serif',
    "ibm-plex": '"IBM Plex Serif", serif',
  };
  return stacks[font] || stacks["literata"];
}

function getReaderSettings() {
  // TODO: Load from settings manager
  return {} as any;
}

function sendProgressUpdate() {
  const state = getState();
  if (!state.currentReader || !state.readerMetadata) return;

  let currentPage = 0;
  let totalPages = 0;

  if (state.currentReader.type === "ebook") {
    currentPage = state.currentReader.currentSpineIndex + 1;
    totalPages = state.currentReader.cif.spine.length;
  } else if (state.currentReader.type === "pdf") {
    totalPages = state.readerMetadata.total_pages || 0;
    currentPage = state.currentReader.currentPage;
  } else if (
    state.currentReader.type === "comic" ||
    state.currentReader.type === "manga"
  ) {
    totalPages = state.currentReader.images.length;
    currentPage = state.currentReader.currentPage;
  }

  updateReadingProgress(state.readerMetadata.media_item_id, {
    current_page: currentPage,
    total_pages: totalPages,
  });

  readerEvents.emit("progressUpdated", { currentPage, totalPages });
}

import { getCurrentPage } from "./reader-state";
