import React, { useRef } from 'react';
import { usePDF, Resolution, Margin } from 'react-to-pdf';
import { CV } from '../types/cv';
import { CVTemplate } from './CVTemplate';

// Extend the Window interface to include our custom property
declare global {
  interface Window {
    generatePDF?: () => void;
  }
}

interface PDFGeneratorProps {
  cv: CV;
}

export const PDFGenerator: React.FC<PDFGeneratorProps> = ({ cv }) => {
  const { toPDF, targetRef } = usePDF({
    filename: `${cv.generalInfo.name || 'CV'}_${new Date().toISOString().slice(0, 10)}.pdf`,
    page: { 
      margin: Margin.MEDIUM, // Using proper margin configuration
      format: 'A4',
      orientation: 'portrait'
    },
    method: 'open',
    resolution: Resolution.HIGH, // Higher resolution for better quality
    overrides: {
      // Overrides for jsPDF for better text selection and rendering
      pdf: {
        compress: true,
        putTotalPages: true,
        floatPrecision: "smart"
      },
      // Overrides for html2canvas for better rendering
      canvas: {
        useCORS: true,
        scale: 2,
        logging: false,
        removeContainer: true
      }
    }
  });

  // Add a method that can be called from outside this component
  React.useEffect(() => {
    // Add a global function that can be called from the parent component
    window.generatePDF = () => {
      console.log("Generating PDF...");
      toPDF();
    };
    
    return () => {
      // Clean up when component unmounts
      delete window.generatePDF;
    };
  }, [toPDF]);

  return (
    <div className="pdf-generator-container">
      <div 
        ref={targetRef} 
        style={{ 
          width: '210mm', // A4 width
          minHeight: '297mm', // A4 height
          padding: '20mm',
          backgroundColor: 'white',
          boxSizing: 'border-box',
          // Remove any borders that might be visible
          border: 'none',
          outline: 'none',
          boxShadow: 'none'
        }}
        className="pdf-template"
      >
        <CVTemplate cv={cv} isPDF={true} />
      </div>
    </div>
  );
}; 