import { usePageTitle } from "@/hooks/usePageTitle";
import type { DocumentSettings } from "@/pages/editor/store/editorStore";
import {
  useGetCatalogById,
  useGetCatalogBySlug,
} from "@/pages/catalogue/hooks/useCatalogueData";
import { type FC, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import BookViewer from "./components/BookViewer";
import ViewerLoading from "./components/ViewerLoading";
import { useBrowserFullscreen } from "./hooks/useBrowserFullscreen";
import { useInitialPagesPreload } from "./hooks/useInitialPagesPreload";
import type { PageData } from "./types";
import { transformViewerDataToPages } from "./utils/dataTransformer";

type ViewerProps = {
  bySlug?: boolean;
};
const Viewer: FC<ViewerProps> = ({ bySlug = false }) => {
  const { id, businessSlug, slug } = useParams<{
    id?: string;
    businessSlug?: string;
    slug?: string;
  }>();
  const catalogKey = bySlug ? slug : id;
  const {
    data,
    isLoading,
    error: queryError,
  } = bySlug
    ? useGetCatalogBySlug(businessSlug ?? "", slug ?? "")
    : useGetCatalogById(id ?? "");
  usePageTitle(`کاتالوگ ${data?.data?.name}`);
  const [pages, setPages] = useState<PageData[]>([]);
  const [documentSettings, setDocumentSettings] = useState<
    Partial<DocumentSettings> | undefined
  >(undefined);

  useEffect(() => {
    if (!data?.data?.content || !catalogKey) return;
    try {
      const parsed = JSON.parse(data.data.content);
      const pagesArray = Array.isArray(parsed) ? parsed : (parsed.pages ?? []);
      const settings: Partial<DocumentSettings> | undefined = Array.isArray(
        parsed,
      )
        ? undefined
        : parsed.documentSettings;
      const transformedPages = transformViewerDataToPages({
        pages: pagesArray,
      } as Parameters<typeof transformViewerDataToPages>[0]);
      setPages(transformedPages);
      setDocumentSettings(settings);
    } catch (err) {
      console.error("خطا در پردازش محتوای کاتالوگ:", err);
    }
  }, [data?.data?.content, catalogKey]);

  useBrowserFullscreen({ enabled: Boolean(catalogKey) });
  const { isReady: areInitialPagesReady, progress: preloadProgress } =
    useInitialPagesPreload(pages, documentSettings);

  if (!catalogKey || (bySlug && !businessSlug)) {
    return (
      <div className="w-full h-full flex items-center justify-center">
        <div className="text-gray-600">شناسه کاتالوگ مشخص نیست</div>
      </div>
    );
  }

  if (isLoading) {
    return <ViewerLoading />;
  }

  if (queryError) {
    return (
      <div className="w-full h-full flex items-center justify-center">
        <div className="text-red-600">خطا: {queryError.message}</div>
      </div>
    );
  }

  if (pages.length === 0) {
    return (
      <div className="w-full h-full flex items-center justify-center">
        <div className="text-gray-600">هیچ صفحه‌ای یافت نشد</div>
      </div>
    );
  }

  if (!areInitialPagesReady) {
    return <ViewerLoading progress={preloadProgress} />;
  }

  return (
    <div className="w-full h-full min-h-0 flex flex-col">
      <BookViewer
        pages={pages}
        catalogSize={data?.data?.size}
        documentSettings={documentSettings}
      />
    </div>
  );
};

export default Viewer;
