'use client'
import React, { forwardRef, useState, useEffect } from 'react';
import HTMLFlipBook from 'react-pageflip';
import { pdfjs, Document, Page as ReactPdfPage } from 'react-pdf';

// Configure PDF.js worker globally
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  'pdfjs-dist/build/pdf.worker.min.mjs',
  import.meta.url,
).toString();

interface PageProps {
  pageNumber: number;
  width: number;
}

interface PDFFlipBookProps {
  pdfUrl: string;
  width?: number;
  height?: number;
  numPages?: number;
}

const DEFAULT_WIDTH = 300;
const DEFAULT_HEIGHT = 424;

const Page = forwardRef<HTMLDivElement, PageProps>(({ pageNumber, width }, ref) => {
  const [pageError, setPageError] = useState<string | null>(null);

  return (
    <div ref={ref} style={{ background: 'white' }}>
      <ReactPdfPage
        pageNumber={pageNumber}
        width={width}
        loading={
          <div className="flex items-center justify-center p-4">
            <div>Loading page {pageNumber}...</div>
          </div>
        }
        error={
          pageError && (
            <div className="text-red-500 p-4">
              Error loading page {pageNumber}: {pageError}
            </div>
          )
        }
        onLoadError={(error) => setPageError(error.message)}
      />
    </div>
  );
});

Page.displayName = 'Page';

const PDFFlipBook: React.FC<PDFFlipBookProps> = ({
  pdfUrl,
  width = DEFAULT_WIDTH,
  height = DEFAULT_HEIGHT,
  numPages = 3,
}) => {
  const [totalPages, setTotalPages] = useState<number>(0);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  const onDocumentLoadSuccess = ({ numPages }: { numPages: number }) => {
    console.log('PDF loaded successfully with', numPages, 'pages');
    setTotalPages(numPages);
    setIsLoading(false);
  };

  const onDocumentLoadError = (error: Error) => {
    console.error('Error loading PDF:', error);
    setError(error.message);
    setIsLoading(false);
  };

  const LoadingComponent = () => (
    <div className="flex items-center justify-center p-4">
      <div className="text-center">
        <div className="text-lg font-medium">Loading PDF...</div>
        <div className="text-sm text-gray-500">Please wait</div>
      </div>
    </div>
  );

  const ErrorComponent = ({ message }: { message: string }) => (
    <div className="flex items-center justify-center p-4">
      <div className="text-center text-red-500">
        <div className="text-lg font-medium">Error loading PDF</div>
        <div className="text-sm">{message}</div>
      </div>
    </div>
  );

  if (error) {
    return <ErrorComponent message={error} />;
  }

  return (
    <Document
      file={pdfUrl}
      onLoadSuccess={onDocumentLoadSuccess}
      onLoadError={onDocumentLoadError}
      loading={<LoadingComponent />}
      error={<ErrorComponent message="Failed to load PDF" />}
      options={{
        cMapUrl: 'cmaps/',
        cMapPacked: true,
        standardFontDataUrl: 'standard_fonts/',
      }}
    >
      {isLoading ? (
        <LoadingComponent />
      ) : (
        <HTMLFlipBook
          style={{}}
          width={width}
          height={height}
          size="fixed"
          minWidth={0}
          maxWidth={0}
          minHeight={0}
          maxHeight={0}
          drawShadow={true}
          flippingTime={1000}
          usePortrait={true}
          startZIndex={0}
          autoSize={true}
          maxShadowOpacity={1}
          showCover={false}
          mobileScrollSupport={true}
          className="pdf-flipbook"
          startPage={0}
          swipeDistance={0}
          showPageCorners={true}
          disableFlipByClick={false}
          clickEventForward={true}
          useMouseEvents={true}
        >
          {Array.from(new Array(Math.min(totalPages, numPages)), (_, index) => (
            <Page key={index + 1} pageNumber={index + 1} width={width} />
          ))}
        </HTMLFlipBook>
      )}
    </Document>
  );
};

export default PDFFlipBook;
