import { getPaperDimensions } from "@/config/paperSizes";
import { clx } from "@/helpers/utils";
import type { Page } from "@/pages/editor/store/editorStore.types";
import BookPage from "@/pages/viewer/components/BookPage";
import type { PageData } from "@/pages/viewer/types";
import { transformViewerDataToPages } from "@/pages/viewer/utils/dataTransformer";
import { type FC, useMemo } from "react";
import type { CatalogItemType } from "../types/Types";

const PREVIEW_WIDTH = 64;
const PREVIEW_HEIGHT = 89;

function getFirstPageFromContent(content: string | undefined): PageData | null {
  if (!content) return null;
  try {
    const parsed = JSON.parse(content);
    const pagesArray = Array.isArray(parsed) ? parsed : (parsed?.pages ?? []);
    const transformed = transformViewerDataToPages({ pages: pagesArray });
    return transformed[0] ?? null;
  } catch {
    return null;
  }
}

function getPageDataFromEditorPage(page: Page): PageData | null {
  const transformed = transformViewerDataToPages({
    pages: [
      {
        id: page.id,
        name: page.name,
        backgroundType: page.backgroundType,
        backgroundColor: page.backgroundColor,
        backgroundGradient: page.backgroundGradient,
        backgroundImageUrl: page.backgroundImageUrl,
        backgroundVideoUrl: page.backgroundVideoUrl,
        objects: page.objects,
      },
    ],
  });
  return transformed[0] ?? null;
}

type Props = {
  item?: CatalogItemType;
  page?: Page;
  size?: string;
  className?: string;
  selected?: boolean;
};

const CatalogPreview: FC<Props> = ({ item, page, size, className, selected }) => {
  const catalogSize = item?.size ?? size ?? "a4";

  const firstPage = useMemo(() => {
    if (page) return getPageDataFromEditorPage(page);
    return getFirstPageFromContent(item?.content);
  }, [item?.content, page]);

  const { pageWidth, pageHeight, previewScale } = useMemo(() => {
    const { width, height } = getPaperDimensions(catalogSize);
    const scale = Math.min(PREVIEW_WIDTH / width, PREVIEW_HEIGHT / height);
    return {
      pageWidth: width,
      pageHeight: height,
      previewScale: scale,
    };
  }, [catalogSize]);

  if (!firstPage) {
    return (
      <div className={clx("bg-gray-200 rounded-lg flex items-center justify-center shrink-0", selected && "border border-black", className)} style={{ width: PREVIEW_WIDTH, height: PREVIEW_HEIGHT }}>
        <span className="text-[10px] text-gray-400 text-center">بدون پیش‌نمایش</span>
      </div>
    );
  }

  return (
    <div
      className={clx("rounded-lg overflow-hidden shrink-0 bg-white border border-gray-200 relative", selected && "border-black", className)}
      style={{ width: PREVIEW_WIDTH, height: PREVIEW_HEIGHT }}
      dir="rtl"
    >
      <div
        className="absolute"
        style={{
          top: 0,
          right: 0,
          transform: `scale(${previewScale})`,
          transformOrigin: "top right",
          width: pageWidth,
          height: pageHeight,
        }}
      >
        <BookPage page={firstPage} scale={1} pageWidth={pageWidth} pageHeight={pageHeight} disableEntranceAnimations staticMedia showPaperShadow={false} />
      </div>
    </div>
  );
};

export default CatalogPreview;
