'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
import { ZoomIn, ZoomOut, Loader2 } from 'lucide-react';
import { useInView } from 'react-intersection-observer';
import 'react-pdf/dist/Page/AnnotationLayer.css';
import 'react-pdf/dist/Page/TextLayer.css';

if (typeof window !== 'undefined') {
  pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;
}

function LazyPage({ pageNumber, scale, containerWidth }: { pageNumber: number; scale: number; containerWidth: number }) {
  const { ref, inView } = useInView({
    triggerOnce: false,
    rootMargin: '150% 0px',
  });

  // Estimate the page height based on typical A4 ratio (1:1.414)
  const estimatedWidth = Math.min(containerWidth * 0.9, 900) * scale;
  const estimatedHeight = estimatedWidth * 1.414;

  return (
    <div 
      ref={ref} 
      className="flex justify-center w-full mb-4"
      style={{ minHeight: inView ? undefined : `${estimatedHeight}px` }}
    >
      {inView ? (
        <Page
          pageNumber={pageNumber}
          scale={scale}
          width={Math.min(containerWidth * 0.9, 900)}
          renderTextLayer={true}
          renderAnnotationLayer={true}
          className="bg-white shadow-xl"
          loading={
            <div 
              className="bg-white shadow-xl flex items-center justify-center" 
              style={{ width: `${estimatedWidth}px`, height: `${estimatedHeight}px` }}
            >
              <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
            </div>
          }
        />
      ) : (
        <div 
          className="bg-gray-100 shadow-xl rounded" 
          style={{ width: `${estimatedWidth}px`, height: `${estimatedHeight}px` }} 
        />
      )}
    </div>
  );
}

export default function PdfViewer({ url }: { url: string }) {
  const [numPages, setNumPages] = useState<number>();
  const [scale, setScale] = useState<number>(1.0);
  const [blobUrl, setBlobUrl] = useState<string | null>(null);
  const [fetchError, setFetchError] = useState<string | null>(null);
  const [fetchingPdf, setFetchingPdf] = useState(true);
  const containerRef = useRef<HTMLDivElement>(null);
  const [containerWidth, setContainerWidth] = useState(800);

  // Measure container width for responsive page sizing
  useEffect(() => {
    const el = containerRef.current;
    if (!el) return;
    const ro = new ResizeObserver(([entry]) => {
      setContainerWidth(entry.contentRect.width);
    });
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  // Fetch the PDF as a blob to avoid Next.js proxy streaming issues with large files
  useEffect(() => {
    let cancelled = false;
    setFetchingPdf(true);
    setFetchError(null);

    fetch(url)
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.blob();
      })
      .then((blob) => {
        if (cancelled) return;
        const objectUrl = URL.createObjectURL(blob);
        setBlobUrl(objectUrl);
      })
      .catch((err) => {
        if (cancelled) return;
        setFetchError(`Failed to load PDF: ${err.message}`);
      })
      .finally(() => {
        if (!cancelled) setFetchingPdf(false);
      });

    return () => {
      cancelled = true;
      if (blobUrl) URL.revokeObjectURL(blobUrl);
    };
  }, [url]); // eslint-disable-line react-hooks/exhaustive-deps

  function onDocumentLoadSuccess({ numPages }: { numPages: number }): void {
    setNumPages(numPages);
  }

  if (fetchingPdf) {
    return (
      <div className="flex flex-col items-center justify-center h-full gap-3">
        <Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--color-accent)' }} />
        <span className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>Loading PDF...</span>
      </div>
    );
  }

  if (fetchError) {
    return (
      <div className="flex flex-col items-center justify-center h-full gap-2">
        <span className="text-sm font-medium" style={{ color: 'var(--color-danger, #ef4444)' }}>{fetchError}</span>
        <a
          href={url}
          target="_blank"
          rel="noreferrer"
          className="px-4 py-2 mt-2 rounded-lg text-sm font-medium transition-opacity hover:opacity-90"
          style={{ backgroundColor: 'var(--color-accent)', color: 'white' }}
        >
          Download Instead
        </a>
      </div>
    );
  }

  return (
    <div className="flex flex-col w-full h-full">
      {/* PDF Toolbar */}
      <div className="flex items-center justify-between p-2 border-b" style={{ borderColor: 'var(--color-border-subtle)', backgroundColor: 'var(--color-bg-elevated)' }}>
        <div className="flex items-center gap-2">
          <span className="text-sm font-medium min-w-[80px] text-center" style={{ color: 'var(--color-text-secondary)' }}>
            {numPages ? `${numPages} page${numPages !== 1 ? 's' : ''}` : 'Loading...'}
          </span>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setScale(s => Math.max(0.5, +(s - 0.25).toFixed(2)))}
            className="p-1 rounded hover:bg-white/10"
            style={{ color: 'var(--color-text-primary)' }}
          >
            <ZoomOut className="w-5 h-5" />
          </button>
          <span className="text-sm font-medium w-12 text-center" style={{ color: 'var(--color-text-secondary)' }}>
            {Math.round(scale * 100)}%
          </span>
          <button
            onClick={() => setScale(s => Math.min(3, +(s + 0.25).toFixed(2)))}
            className="p-1 rounded hover:bg-white/10"
            style={{ color: 'var(--color-text-primary)' }}
          >
            <ZoomIn className="w-5 h-5" />
          </button>
        </div>
      </div>
      
      {/* PDF Content */}
      <div ref={containerRef} className="flex-1 overflow-auto bg-neutral-100 dark:bg-neutral-900 py-4 flex flex-col items-center">
        <Document
          file={blobUrl!}
          onLoadSuccess={onDocumentLoadSuccess}
          onLoadError={(error) => console.error('Failed to load PDF:', error)}
          loading={
            <div className="flex items-center justify-center h-full mt-20">
              <Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--color-accent)' }} />
            </div>
          }
          className="flex flex-col items-center gap-2 w-full"
        >
          {numPages && Array.from(new Array(numPages), (_, index) => (
            <LazyPage 
              key={`page_${index + 1}`} 
              pageNumber={index + 1} 
              scale={scale}
              containerWidth={containerWidth}
            />
          ))}
        </Document>
      </div>
    </div>
  );
}
